Vue组件data选项为什么必须是个函数而Vue的根实例则没有此限制?

198 阅读1分钟

vue组件的配置(options)和vue实例(instance)是需要分开的。最根本原因是js对于对象(以及数组等)是传引用的,因为如果直接写一个对象进去,那么当依此配置初始化了多个实例之后,这个对象必定是多个实例共享的。 距离为说明: 例子1

vueconfig = {
  data: {
    name: 'foo'
  }
};
 
function someComponent (config) {
  this.data = config.data;
}
 
let c1 = new someComponent(vueconfig);
 
let c2 = new someComponent(vueconfig);
 
c1.data.name = 'bar';
console.log(c2.data.name); // 'bar'

例子2

config = {
  data: function () {
    return {
      txt: 'inittxt'
    };
  }
};
 
function someComponent (config) {
  this.data = config.data();
}
 
let c1 = new someComponent(config);
 
let c2 = new someComponent(config);
 
c1.data.txt = 'aaa';
 
console.log(c2.data.name); // 'inittxt'