Vue组件中data选项为什么必须是函数

官方解释

data 必须是函数
构造 Vue 实例时传入的各种选项大多数都可以在组件里使用。只有一个例外:data 必须是函数。实际上,如果你这么做:

Vue.component('my-component', {
  template: '<span>{{ message }}</span>',
  data: {
    message: 'hello'
  }
})

那么 Vue 会停止运行,并在控制台发出警告,告诉你在组件实例中 data 必须是一个函数。但理解这种规则为何存在也是很有益处的,所以让我们先作个弊:

<div id="example-2">
  <simple-counter></simple-counter>
  <simple-counter></simple-counter>
  <simple-counter></simple-counter>
</div>
var data = { counter: 0 }
Vue.component('simple-counter', {
  template: '<button v-on:click="counter += 1">{{ counter }}</button>',
  ```
  // 技术上 data 的确是一个函数了,因此 Vue 不会警告,
  // 但是我们却给每个组件实例返回了同一个对象的引用
  ```
  data: function () {
    return data
  }
})
new Vue({
  el: '#example-2'
})

=============以下为个人理解,如果有误,请指出,谢谢指教

Vue.component('xxx',{
template:'{{counter}}',
data:function(){
return counter=0;
}
})

Vue在注册到全局/局部并生成实例时,它是具有自己的作用域的,也就是说
在template 字符串模板中如果存在一个变量名与VUE实例的变量名一致的时候,这个变量只会是组件中的变量,而不会是VUE的全局变量

比如

//以下代码中,组件中的count和Vue中的count是一样的变量名,但是在组件中只会显示0而不是2
Vue.component('simple-counter',{
                template:'<button>{{count}}</button>',
                data:function(){
                    return count=0;

                }

            });
            vm=new Vue({
                el:'#example-2',
                data:{
                    count:2

                }

            })

以上代码从原型链上理解

var component=function(){}//为了让组件有自己的作用域,它必须包含私有变量data,所以简单化的理解应该是这样的

var component=function(){
this.data=this.data();//存在私有的data属性
}

component.propotype.data=function(){
return {count:0}
}
//当我们在template中使用数据的时候,我们是调用的component的私有变量data
//如果我们不以函数的形式处理又会如何呢?
var component=function(){
//不存在私有的data属性
}
component.propotype.data= {count:0}
//此时,data不作为私有变量,就会有暴露的风险,而且,它指向的是{count:0}的引用,所以当重复创建组件的时候,component的data都指向了同一个引用。因此会相互影响。

如果不以原型链的形式处理,也可以不传入函数

function component(d) {

                this.data = d;
            }
var com = new component({
                count: 1
            });
            var com1 = new component({
                count: 1
            });             
发布了108 篇原创文章 · 获赞 44 · 访问量 52万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章