vue data中的this指向问题

 

 在data里定义Object类型的变量时,会发现Object中访问不到vue的this属性。

例如:

 1 export default {
 2   data(){
 3     return {
 4       a: "123",
 5       b: {
 6         c: this.a
 7       }
 8     };
 9   },
10   created() {
11     console.log("b: ", this.b.c); // undefined
12   }
13 }

想在b中访问this.a的数据,直接访问会返回undefined,因为这时c中的this指向的是b。

这种情况可以用到Object的get属性进行属性定义。

例如:

 1 export default {
 2   data(){
 3     return {
 4       a: "123",
 5       b: {
 6         _target: () => this,
 7         get target() {
 8           return this._target();
 9         },
10         
11         get c() {
12           return this.target.a;
13         },
14       },
15     };
16   },
17   created() {
18     console.log("b: ", this.b.c); // 123
19   }
20 }

此处将this映射到了Object变量内部,然后通过get的形式定义属性并获取。

 

当get定义的属性所依赖的属性的值发生改变时,get定义的属性的值也将发生改变。

例如:

 1 export default {
 2   data(){
 3     return {
 4       a: "123",
 5       b: {
 6         _target: () => this,
 7         get target() {
 8           return this._target();
 9         },
10 
11         get c() {
12           return this.target.a;
13         },
14 
15         d: 123,
16 
17         get e() {
18           return `依赖于d的值, 会同步发生改变, d的值为: ${this.d}`;
19         }
20       },
21     };
22   },
23   created() {
24     console.log("b: ", this.b.c); // 123
25 
26     console.log("e: ", this.b.e); // e:  依赖于d的值, 会同步发生改变, d的值为: 123 c: 123
27 
28     setTimeout(() => {
29       this.b.d = 456;
30       console.log("e: ", this.b.e); // e:  依赖于d的值, 会同步发生改变, d的值为: 456 c: 123
31     }, 1000);
32 
33     setTimeout(() => {
34       this.a = "456";
35       console.log("e: ", this.b.e); // e:  依赖于d的值, 会同步发生改变, d的值为: 456 c: 456
36     }, 2000);
37   }
38 }

当前方法更像是一种深度计算属性(computed),会随着所依赖的项发生改变而改变。

 

​转载自:https://blog.csdn.net/s4944315/article/details/120313437

posted @ 2021-09-16 11:07  Bensun  阅读(1952)  评论(0编辑  收藏  举报