vue工作机制

vue 工作机制

Vue响应式的原理defineProperty

 1 class KVue {
 2 constructor(options) {
 3 this._data = options.data;
 4 this.observer(this._data);
 5 }
 6 observer(value) {
 7 if (!value || typeof value !== "object") {
 8 return;
 9 }
10 Object.keys(value).forEach(key => {
11 this.defineReactive(value, key, value[key]);
12 });
13 }
14 defineReactive(obj, key, val) {
15 Object.defineProperty(obj, key, {
16 enumerable: true /* 属性可枚举 */,
17 configurable: true /* 属性可被修改或删除 */,
18 get() {
19 return val;
20 },
21 set(newVal) {
22 if (newVal === val) return;
23 this.cb(newVal);
24 }
25 });
26 }
27 cb(val) {
28 console.log("更新数据了", val);
29 }
30 }
31 let o = new KVue({
32 data: {
33 test: "I am test."
34 }
35 });
36 o._data.test = "hello,kaikeba";

猜你喜欢

转载自www.cnblogs.com/yangshuzhong/p/11412236.html