Vue组件为什么data必须是一个函数

前言

我们需要先复习下原型链的知识,其实这个问题取决于 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 ,没有问题!
总结
自己突然对这个问题懵逼,不过事后想了想还是自己基础知识忘得太快。以前学习 js 的时候,最基础的:构造函数内和原型之间的区别都模糊了。想不到 vue 这个小问题让我温故而知新了一次。
到此这篇关于Vue组件为什么data必须是一个函数的文章就介绍到这了,更多相关Vue组件data是函数内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

相关推荐

评论

展开