內(nèi)容介紹:
- watch屬性介紹
- watch屬性谈宛,觀測值的三種寫法
- watch觀測對象注意不能使用箭頭函數(shù)
- watch的實戰(zhàn)-觀測數(shù)組內(nèi)所有對象的某個值的變化
watch屬性:watch是vue實列的一個屬性分蓖,它是一個對象,鍵是需要觀察的表達式蝇刀,值是對應回調(diào)函數(shù)。值也可以是方法名,或者包含選項的對象旷偿。Vue 實例將會在實例化時調(diào)用 $watch()速缆,遍歷 watch 對象的每一個屬性哥桥。
var vm = new Vue({
data: {
a: 1,
b: 2,
c: 3
},
watch: {
//第一種寫法 適用于普通變量(簡單類型的值的觀測寫法)
a: function (val, oldVal) {
console.log('new: %s, old: %s', val, oldVal)
},
// 第二種寫法:方法名
b: 'someMethod',
// 第三種寫法:深度 watcher(能觀測對象c下多重屬性變化)(復雜類型的值的觀測寫法)
c: {
//當c變化后會回調(diào)handler函數(shù)
handler: function (val, oldVal) { /* ... */ },
deep: true
}
}
})
vm.a = 2 // -> new: 2, old: 1
** 注意:不能使用箭頭函數(shù)定義watcher(回調(diào))函數(shù),因為箭頭函數(shù)綁定了父級作用域的上下文激涤,所以里面的 this 將不會按照期望指向 Vue 實例**
watch: {
// 這里面的this指向了vue實列 ----Vue$3 {_uid: 0, _isVue: true, $options: Object, _renderProxy: Proxy, _self: Vue$3…}
a: function (val, oldVal) {
console.log('new: %s, old: %s', val, oldVal)
},
// 箭頭函數(shù):這里的this指向的是window-----Window {stop: function, open: function, alert: function, confirm: function, prompt: function…}
b:()=>{
console.log(this.a);
},
// 深度 watcher
c: {
handler: function (val, oldVal) { /* ... */ },
deep: true
}
}
watch的實戰(zhàn)-觀測數(shù)組內(nèi)所有對象的某個值的變化:
我們常常會遇到請求回來的數(shù)據(jù)拟糕,計算訂單的數(shù)量和或價格,值變化的時候數(shù)量顯示也要變化:
<body>
<div id="app">
<span>{{count}}</span>
</div>
<script>
var vm = new Vue({
el:'#app',
data: {
count:0,
items : [
{
id: 336,
title: '炒肉',
count: 1,
price: 106
},
{
id: 337,
title: '生菜',
count: 2,
price: 225
}
]
},
watch: {
"items":{
handler(){
this.count = 0
this.items.forEach((item)=>{
this.count +=item.count
});
},
deep:true
}
}
})
</script>
</body>
11-watch屬性.gif