Explain in detail why the data option in the component of Vue must be a function
- 2021-08-06 20:39:27
- OfStack
Official explanation
data must be a function
Most of the various options passed in when constructing Vue instances can be used in components. There is only one exception: data must be a function. In fact, if you do this:
Vue.component('my-component', {
template: '<span>{{ message }}</span>',
data: {
message: 'hello'
}
})
Then Vue will stop running and a warning will be issued in the console telling you that data must be a function in the component instance. But it is also beneficial to understand why this rule exists, so let's make a mistake first:
<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>',
```
// Technically data Indeed it is 1 Functions, so Vue No warning,
// But we return the same for each component instance 1 A reference to an object
```
data: function () {
return data
}
})
new Vue({
el: '#example-2'
})
=
Vue.component('xxx',{
template:'{{counter}}',
data:function(){
return counter=0;
}
})
Vue has its own scope when registering with global/local and generating instances, that is
If there is a variable name in the template string template that matches the variable name of the VUE instance, this variable will only be a component variable, not a global variable of VUE
For example
// In the following code, the count And Vue In count Yes 1 The variable name of the sample, but only the variable name will be displayed in the component 0 Instead of 2
Vue.component('simple-counter',{
template:'<button>{{count}}</button>',
data:function(){
return count=0;
}
});
vm=new Vue({
el:'#example-2',
data:{
count:2
}
})
The above code is understood from the prototype chain
var component=function(){}// In order for a component to have its own scope, it must contain private variables data So the simplistic understanding should be like this
var component=function(){
this.data=this.data();// There is a private data Attribute
}
component.propotype.data=function(){
return {count:0}
}
// When we're in template When using data in, we call the component Private variables of data
// What if we don't deal with it as a function?
var component=function(){
// There is no private data Attribute
}
component.propotype.data= {count:0}
// At this point, data Not as a private variable, there is a risk of exposure, and it points to {count:0} So when creating components repeatedly, component Adj. data They all point to the same 1 A reference. Therefore, they will influence each other.
If it is not processed in the form of prototype chain, it is also possible not to pass in functions
function component(d) {
this.data = d;
}
var com = new component({
count: 1
});
var com1 = new component({
count: 1
});
Summarize