淺談 vue 中的 watcher
觀察 Watchers
雖然計(jì)算屬性在大多數(shù)情況下更合適,但有時(shí)也需要一個(gè)自定義的 watcher 。這是為什么 Vue 提供一個(gè)更通用的方法通過(guò)watch 選項(xiàng),來(lái)響應(yīng)數(shù)據(jù)的變化。當(dāng)你想要在數(shù)據(jù)變化響應(yīng)時(shí),執(zhí)行異步操作或開(kāi)銷較大的操作,這是很有用的。
大家對(duì)于 watch 應(yīng)該不陌生,項(xiàng)目中都用過(guò)下面這種寫法:
watch: { someProp () { // do something } } // 或者 watch: { someProp: { deep: true, handler () { // do something } } }
上面的寫法告訴 vue,我需要監(jiān)聽(tīng) someProp 屬性的變化,于是 vue 在內(nèi)部就會(huì)為我們創(chuàng)建一個(gè) watcher 對(duì)象。(限于篇幅,我們不聊 watcher 的具體實(shí)現(xiàn),感興趣的可以直接看源碼 watcher)
然而在 vue 中,watcher 的功能并沒(méi)有這么單一,先上段代碼:
<template> <div> <p>a: {{ a }}</p> <p>b: {{ b }}</p> <button @click="increment">+</button> </div> </template> <script> export default { data () { return { a: 1 } }, computed: { b () { return this.a * 2 } }, watch: { a () { console.log('a is changed') } }, methods: { increment () { this.a += 1 } }, created () { console.log(this._watchers) } } </script>
上面代碼非常簡(jiǎn)單,我們現(xiàn)在主要關(guān)注 created 鉤子中打印的 this._watchers,如下:
分別展開(kāi)三個(gè) watcher,觀察每一個(gè) expression,從上到下分別為:
b() { return this.a * 2;↵ } "a" function () { vm._update(vm._render(), hydrating);↵ }
上面三個(gè) watcher 代表了三種不同功能的 watcher,我們將其按功能分為三類:
- 在 watch 中定義的,用于監(jiān)聽(tīng)屬性變化的 watcher (第二個(gè))
- 用于 computed 屬性的 watcher (第一個(gè))
- 用于頁(yè)面更新的 watcher (第三個(gè))
normal-watcher
我們?cè)?watch 中定義的,都屬于這種類型,即只要監(jiān)聽(tīng)的屬性改變了,都會(huì)觸發(fā)定義好的回調(diào)函數(shù)
computed-watcher
每一個(gè) computed 屬性,最后都會(huì)生成一個(gè)對(duì)應(yīng)的 watcher 對(duì)象,但是這類 watcher 有個(gè)特點(diǎn),我們拿上面的 b 舉例:
屬性 b 依賴 a,當(dāng) a 改變的時(shí)候,b 并不會(huì)立即重新計(jì)算,只有之后其他地方需要讀取 b 的時(shí)候,它才會(huì)真正計(jì)算,即具備 lazy(懶計(jì)算)特性
render-watcher
每一個(gè)組件都會(huì)有一個(gè) render-watcher, function () {↵ vm._update(vm._render(), hydrating);↵ }
, 當(dāng) data/computed
中的屬性改變的時(shí)候,會(huì)調(diào)用該 render-watcher 來(lái)更新組件的視圖
三種 watcher 的執(zhí)行順序
除了功能上的區(qū)別,這三種 watcher 也有固定的執(zhí)行順序,分別是:
computed-render -> normal-watcher -> render-watcher
這樣安排是有原因的,這樣就能盡可能的保證,在更新組件視圖的時(shí)候,computed 屬性已經(jīng)是最新值了,如果 render-watcher 排在 computed-render 前面,就會(huì)導(dǎo)致頁(yè)面更新的時(shí)候 computed 值為舊數(shù)據(jù)。
下面從一段實(shí)例代碼中看下vue中的watcher
在這個(gè)示例中,使用 watch 選項(xiàng)允許我們執(zhí)行異步操作(訪問(wèn)一個(gè) API),限制我們執(zhí)行該操作的頻率,并在我們得到最終結(jié)果前,設(shè)置中間狀態(tài)。這是計(jì)算屬性無(wú)法做到的。
<div id="watch-example"> <p> Ask a yes/no question: <input v-model="question"> </p> <p>{{ answer }}</p> </div> <!-- Since there is already a rich ecosystem of ajax libraries --> <!-- and collections of general-purpose utility methods, Vue core --> <!-- is able to remain small by not reinventing them. This also --> <!-- gives you the freedom to just use what you're familiar with. --> <script src="https://unpkg.com/axios@0.12.0/dist/axios.min.js"></script> <script src="https://unpkg.com/lodash@4.13.1/lodash.min.js"></script> <script> var watchExampleVM = new Vue({ el: '#watch-example', data: { question: '', answer: 'I cannot give you an answer until you ask a question!' }, watch: { // 如果 question 發(fā)生改變,這個(gè)函數(shù)就會(huì)運(yùn)行 question: function (newQuestion) { this.answer = 'Waiting for you to stop typing...' this.getAnswer() } }, methods: { // _.debounce 是一個(gè)通過(guò) lodash 限制操作頻率的函數(shù)。 // 在這個(gè)例子中,我們希望限制訪問(wèn)yesno.wtf/api的頻率 // ajax請(qǐng)求直到用戶輸入完畢才會(huì)發(fā)出 // 學(xué)習(xí)更多關(guān)于 _.debounce function (and its cousin // _.throttle), 參考: https://lodash.com/docs#debounce getAnswer: _.debounce( function () { var vm = this if (this.question.indexOf('?') === -1) { vm.answer = 'Questions usually contain a question mark. ;-)' return } vm.answer = 'Thinking...' axios.get('https://yesno.wtf/api') .then(function (response) { vm.answer = _.capitalize(response.data.answer) }) .catch(function (error) { vm.answer = 'Error! Could not reach the API. ' + error }) }, // 這是我們?yōu)橛脩敉V馆斎氲却暮撩霐?shù) 500 ) } }) </script>
小結(jié)
本文并不是源碼解析類文章,只是從一個(gè)角度來(lái)聊聊,那些看似不相關(guān)的東西(computed/watch/頁(yè)面更新),內(nèi)部卻有著緊密的聯(lián)系,希望能拋磚引玉,讓大家更深入的去探索 vue
- Vue.js中關(guān)于偵聽(tīng)器(watch)的高級(jí)用法示例
- Vue數(shù)據(jù)監(jiān)聽(tīng)方法watch的使用
- vue watch監(jiān)聽(tīng)對(duì)象及對(duì)應(yīng)值的變化詳解
- 關(guān)于vue中watch檢測(cè)到不到對(duì)象屬性的變化的解決方法
- vue進(jìn)行圖片的預(yù)加載watch用法實(shí)例講解
- vue watch自動(dòng)檢測(cè)數(shù)據(jù)變化實(shí)時(shí)渲染的方法
- vue組件watch屬性實(shí)例講解
- Vue2.0用 watch 觀察 prop 變化(不觸發(fā))
- 詳解vue2 $watch要注意的問(wèn)題
- 詳解Vue中watch的高級(jí)用法
相關(guān)文章
Vue3中的setup執(zhí)行時(shí)機(jī)與注意點(diǎn)說(shuō)明
這篇文章主要介紹了Vue3中的setup執(zhí)行時(shí)機(jī)與注意點(diǎn)說(shuō)明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-07-07淺談實(shí)現(xiàn)在線預(yù)覽PDF的幾種解決辦法
這篇文章主要介紹了淺談實(shí)現(xiàn)在線預(yù)覽PDF的幾種解決辦法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-08-08vue 路由視圖 router-view嵌套跳轉(zhuǎn)的實(shí)現(xiàn)
這篇文章主要介紹了vue 路由視圖 router-view嵌套跳轉(zhuǎn),主要實(shí)現(xiàn)的內(nèi)容有制作一個(gè)登錄頁(yè)面,跳轉(zhuǎn)到首頁(yè),首頁(yè)包含菜單欄、頂部導(dǎo)航欄、主體,標(biāo)準(zhǔn)的后臺(tái)網(wǎng)頁(yè)格式,菜單點(diǎn)擊顯示不同的頁(yè)面,感興趣的小伙伴請(qǐng)參考下面文章內(nèi)容2021-09-09如何在vue3中同時(shí)使用tsx與setup語(yǔ)法糖
這篇文章主要介紹了如何在vue3中同時(shí)使用tsx與setup語(yǔ)法糖,文章圍繞主題展開(kāi)詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-09-09