watch 是用來即時監聽資料變化,像是使用者輸入搜尋關鍵字,要即時更新結果、表單內容變更時,要自動儲存等等,這些都需要偵測資料的變化。
<script setup>
import { ref, watch } from 'vue'
const keyword = ref('')
watch(keyword, (newVal, oldVal) => {
console.log(`搜尋關鍵字從 ${oldVal} 變成 ${newVal}`)
})
</script>
<template>
<input v-model="keyword" placeholder="輸入搜尋關鍵字" />
</template>
import { ref, watch } from 'vue'
const keyword = ref('')
const year = ref('114')
watch([keyword, year], ([newKeyword, newYear], [oldKeyword, oldYear]) => {
console.log('keyword 改變:', oldKeyword, '→', newKeyword)
console.log('year 改變:', oldYear, '→', newYear)
})
watch 只會監聽第一層變化,若是有多層的資料,像是物件、陣列等等,則需要使用到深度監聽
import { reactive, watch } from 'vue'
const form = reactive({
name: '小明',
score: 80
})
watch(form, (newVal) => {
console.log('變化:', newVal)
})
form.name = '小美'
這樣 watch 不會被觸發,因為 watch 看的是 form 整個物件有沒有改變,而不是資料內容有沒有改變,因此這時候就需要用到深度監聽,範例如下:
watch(form, (newVal) => {
console.log('偵測到變化:', newVal)
}, { deep: true })
當再次執行上面 form.name = '小美' 的程式碼時,watch 就會成功監聽到變化
小結
- 監聽基本範例
- 監聽多個變數
- 深度監聽用法與適用範圍