19.vue组件中data为什么必须是一个函数

https://www.jb51.net/article/188491.htm

前言

我们需要先复习下原型链的知识,其实这个问题取决于 js ,而并非是 vue 。

1
2
3
4
5
6
7
function Component(){
 this.data = this.data
}
Component.prototype.data = {
  name:'jack',
  age:22,
}

首先我们达成一个共识(没有这个共识,请补充下 js 原型链部分的知识):

  • 实例它们构造函数内的this内容是不一样的。
  • Component.prototype ,这类底下的方法或者值,都是所有实例公用的。

解开疑问

基于此,我们来看看这个问题:

1
2
3
4
5
6
7
8
9
10
11
function Component(){
  
}
Component.prototype.data = {
  name:'jack',
  age:22,
}
var componentA = new Component();
var componentB = new Component();
componentA.data.age=55;
console.log(componentA,componentB)

此时,componentA 和 componentB data之间指向了同一个内存地址,age 都变成了 55, 导致了问题!

接下来很好解释为什么 vue 组件需要 function 了:

1
2
3
4
5
6
7
8
9
10
11
12
13
function Component(){
 this.data = this.data()
}
Component.prototype.data = function (){
  return {
  name:'jack',
  age:22,
}
}
var componentA = new Component();
var componentB = new Component();
componentA.data.age=55;
console.log(componentA,componentB)

此时,componentA 和 componentB data之间相互独立, age 分别是 55 和 22 ,没有问题!

posted @ 2020-08-13 21:46  大牛半路出家  阅读(565)  评论(0编辑  收藏  举报