1.watch監聽器會監聽data中數據的變化,只要一變化,就能夠執行相應的邏輯
2.監聽的數據名放到這里面作為函數名,這個函數里面有兩個參數,一個是新值,一個是舊值
<div id="app">
<input type="text" v-model="firstName">
<input type="text" v-model="lastName">
<h1>全名:{{fullName}}</h1>
</div>
<script>
var vm = new Vue({
el: '#app',
data: {
firstName: '',
lastName: '',
fullName: ''
},
watch: {
firstName(newVal, oldVal) {
console.log(newVal, oldVal)
// 要用一個變量,將得到的數據保存起來
this.fullName = newVal + this.lastName
},
lastName(newVal, oldVal) {
setTimeout(() => {
this.fullName = this.firstName + newVal
}, 200);
}
}
})
</script>
與computed比較:
- 對比computed而言,這個computed性能更好,所以能用computed實現就用computed實現。
- 在涉及到異步數據操作的時候,就只能用watch去實現了。