watch 是監聽屬性,當在數據發生變化時,需要執行異步或比較複雜的操作,watch 會比 computed 適合。watch 的 callback 裡會傳入監聽的新舊值。
以下面範例來說,當使用者輸入問題時,會執行 watch 的 question function,並且執行 getAnswer 訪問 https://yesno.wtf/api
取得問題的答案
<div id="watch-example">
<p>
Ask a yes/no question:
<input v-model="question">
</p>
<p>{{ answer }}</p>
</div>
<script src="https://cdn.jsdelivr.net/npm/axios@0.12.0/dist/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/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` 發生改變,此函數就會執行
question: function (newQuestion, oldQuestion) {
this.answer = 'Waiting for you to stop typing...'
this.debouncedGetAnswer()
}
},
created() {
// `_.debounce` 是 lodash.js 的 debounce 函數,限制操作频率的函数
// 此處希望限制訪問 yesno.wtf/api 的频率
// 在使用者输入停止 500 毫秒後,確認問題包含 `?` 才會發出 AJAX 請求
this.debouncedGetAnswer = _.debounce(this.getAnswer, 500)
},
methods: {
getAnswer: function () {
if (this.question.indexOf('?') === -1) {
this.answer = 'Questions usually contain a question mark. ;-)'
return
}
this.answer = 'Thinking...'
var vm = this
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
})
}
}
})
</script>
watch 也是發生在 Vue 實例初始化的 initState 中
// src/core/instance/state.js
// ...
export function initState (vm: Component) {
vm._watchers = []
const opts = vm.$options
if (opts.props) initProps(vm, opts.props)
if (opts.methods) initMethods(vm, opts.methods)
if (opts.data) {
initData(vm)
} else {
observe(vm._data = {}, true)
}
if (opts.computed) initComputed(vm, opts.computed)
/*************************************************
此處執行了 initWatch
**************************************************/
if (opts.watch && opts.watch !== nativeWatch) {
initWatch(vm, opts.watch)
}
}
//...
/*************************************************
定義 initWatch
**************************************************/
function initWatch (vm: Component, watch: Object) {
for (const key in watch) {
const handler = watch[key]
if (Array.isArray(handler)) {
for (let i = 0; i < handler.length; i++) {
createWatcher(vm, key, handler[i])
}
} else {
createWatcher(vm, key, handler)
}
}
}