偵聽組件實例上的響應式 property 或函數計算結果的變化。回調函數得到的參數為新值和舊值。
我們只能將頂層的 data、prop 或 computed property 名作為字符串傳遞。對於更複雜的表達式,用一個函數取代。
假設 data 定義的數據如下:
data() { return { a: 1, b: 2, c: { d: 3, e: 4 } }}單個的頂層屬性,第一個參數是字符串,第二個參數是函數。
created() { this.$watch('a', (newVal, oldVal) => { })}包含嵌套的對象裡面的屬性,兩個參數都必須是函數形式。
created() { this.$watch( () => this.c.d, (newVal, oldVal) => { } )}如果使用的是 vue3 請使用上面的寫法,如果使用的是 vue2 可以使用簡單的鍵路徑。
created() { this.$watch('c.d', (newVal, oldVal) => { })}對於更複雜的表達式,用一個函數取代。
created() { this.$watch( () => this.a + this.b, (newVal, oldVal) => { } )}當偵聽的值是一個對象或者數組時,對其屬性或元素的任何更改都不會觸發偵聽器,因為它們引用相同的對象/數組:
const app = Vue.createApp({ data() { return { article: { text: 'Vue is awesome!' }, comments: ['Indeed!', 'I agree'] } }, created() { this.$watch('article', () => { console.log('Article changed!') })
this.$watch('comments', () => { console.log('Comments changed!') }) }, methods: { changeArticleText() { this.article.text = 'Vue 3 is awesome' }, addComment() { this.comments.push('New comment') },
changeWholeArticle() { this.article = { text: 'Vue 3 is awesome' } }, clearComments() { this.comments = [] } }})為了發現對象內部值的變化,可以在選項參數中指定 deep: true。在選項參數中指定 immediate: true 將立即以表達式的當前值觸發回調:
created() { this.$watch('c', (newVal, oldVal) => { }, { deep: true, immediate: true })}注意:在變更 (不是替換) 對象或數組時,舊值將與新值相同,因為它們的引用指向同一個對象/數組。Vue 不會保留變更之前值的副本。
$watch 返回一個取消偵聽函數,用來停止觸發回調。
命令式的 $watch API,和 options API 中的 watch 選項類似,但是和 composition API 的 watch 還是有點區別的。因為後者可以使用數組來同時偵聽多個源:
watch([fooRef, barRef], ([foo, bar], [prevFoo, prevBar]) => { })需要在數據變化時執行異步或開銷較大的操作時,請使用 watch 處理。