創建 Vue 實例時,Vue 會遍歷 data 上的屬性,通過 ES5 的 Object.defineProperty 把它們轉成 getter/setter。正是這層轉換,讓 Vue 內部得以追蹤依賴、通知變化。
const vm = new Vue({
data: { foo: 1 }
// 內部訪問的 'this.foo' 與外部的 'vm.foo' 是響應的
});
const vm = new Vue({ data: { foo: 1 } });
vm.$watch('foo', function (newValue, oldValue) {
console.log(newValue, oldValue); // 2 1
console.log(this.foo); // 2,this 自動綁定到 vm
});
vm.foo = 2;
注意:回調是異步的。
vm.$watch('foo', function (newValue) {
console.log('inner:', newValue); // 後輸出 inner 2
});
vm.foo = 2;
console.log('outer:', vm.foo); // 先輸出 outer 2
這正是數據與視圖綁定的基礎:Vue 觀察到數據變化後,並不立刻改 DOM,而是異步更新。同一個事件循環內的多次修改會被緩存,等到下一個循環再刷新隊列、只執行必要的更新。
vm.$watch('foo', function (newValue) {
console.log('inner:', newValue); // 只輸出一次 inner 5
});
vm.foo = 2;
vm.foo = 3;
vm.foo = 4;
console.log('outer:', vm.foo); // outer 4
vm.foo = 5;
MV* 框架裡,把 Model 的數據呈現到 View 往往需要一層加工。這種場景下,計算屬性(computed property)比在模板裡堆表達式明智得多。
const vm = new Vue({
data: { width: 0, height: 0 },
computed: {
area() {
let output = '';
if (this.width > 0 && this.height > 0) {
const area = this.width * this.height;
output = area.toFixed(2) + 'm²';
}
return output;
}
}
});
vm.width = 2.34;
vm.height = 5.67;
console.log(vm.area); // 13.27m²
計算屬性內部 this 會自動綁定到 vm,所以不要用箭頭函數聲明 computed,否則 this 會指向外層作用域。
它的核心優勢是依賴緩存:vm.area 首次求值時,Vue 收集 this.width 與 this.height 作為其依賴;此後只要這兩個值變化才重新計算,否則多次讀取直接返回上次結果。
由於依賴是響應的,還可以把屬性先解構給局部變量,既減少屬性讀取次數,也能規避「條件分支中 Vue 偶爾收集不到依賴」的問題:
computed: {
area() {
let output = '';
const { width, height } = this;
if (width > 0 && height > 0) {
output = (width * height).toFixed(2) + 'm²';
}
return output;
}
}
為了方便學習與複用,有人把 Vue 的屬性觀察模塊抽離出來做了個小庫 ob.js。
地址:https://github.com/cnlon/ob.js
npm install --save ob.js
觀察屬性變化:
const target = { a: 1 };
ob(target, 'a', function (newValue, oldValue) {
console.log(newValue, oldValue); // 3 1
});
target.a = 3;
添加計算屬性:
const target = { a: 1 };
ob.compute(target, 'b', function () {
return this.a * 2;
});
target.a = 10;
console.log(target.b); // 20
像聲明 Vue 實例那樣傳入整份配置:
const options = {
data: {
PI: Math.PI,
radius: 1
},
computed: {
'area': function () {
return this.PI * this.square(this.radius);
}
},
watchers: {
'area': function (newValue) {
console.log(newValue); // 28.274333882308138
}
},
methods: {
square(num) { return num * num; }
}
};
const target = ob.react(options);
target.radius = 3;
理解這套機制有一個現實意義:Vue 2 的響應式依賴 Object.defineProperty,因此無法感知對象新增屬性與數組下標賦值,需要用 this.$set 或操作數組的變異方法;Vue 3 改用 Proxy 才把這兩個限制消除。知道原理,才知道邊界在哪。
以上就是這篇文章的全部內容,希望對大家的學習或工作有所幫助。有疑問歡迎留言交流。