When building componentized applications using Vue, each component’s data property is returned as a function, mainly because each instance can maintain a separate copy of the returned object, rather than sharing references to the same object, at componentized implementation time
Vue simple instance
In a Vue simple instance, that is, without a componentized implementation, data can be an object, and since there is only one instance of itself, there is no problem with multiple instances sharing
<! DOCTYPEhtml>
<html>
<head>
<title>Vue</title>
</head>
<body>
<div id="app">
<div>{{msg}}</div>
</div>
</body>
<script src="https://cdn.bootcss.com/vue/2.4.2/vue.js"></script>
<script type="text/javascript">
let vm = new Vue({
el: "#app".data: {
msg: "Vue Instance"}})</script>
</html>
Copy the code
Componentized instance
If you are using a componentized instance of Vue, the data attribute must be returned as a function. If you are not returning as a function, some unexpected situations may occur. For example, in the following example, the button component is reused and there should be only one button +1 when the first button is clicked. But all buttons follow +1. Attention, please. Here is still using the function returns, this is because if the modular implementation if you do not use function returns the Vue will direct error, but the implementation effect is the same, although is returned in the form of function, but the count property in the object returned are pointing to the object reference for counter, Essentially, multiple component instances share an object, and the actual effect is returned directly as an object
<! DOCTYPEhtml>
<html>
<head>
<title>Vue</title>
</head>
<body>
<div id="app">
<button-counter></button-counter>
<button-counter></button-counter>
<button-counter></button-counter>
</div>
</body>
<script src="https://cdn.bootcss.com/vue/2.4.2/vue.js"></script>
<script type="text/javascript">
let counter = {
count: 0;
}
Vue.component("button-counter", {
data: function() {
return counter;
},
template: `<button v-on:click="count++">You clicked me {{count}} times.</button>`
})
let vm = new Vue({
el: "#app"
})
</script>
</html>
Copy the code
So to get around this, in componentized implementations, the data attribute must be returned as a function so that each instance maintains a separate copy of the returned object, rather than sharing a reference to the same object
<! DOCTYPEhtml>
<html>
<head>
<title>Vue</title>
</head>
<body>
<div id="app">
<button-counter></button-counter>
<button-counter></button-counter>
<button-counter></button-counter>
</div>
</body>
<script src="https://cdn.bootcss.com/vue/2.4.2/vue.js"></script>
<script type="text/javascript">
Vue.component("button-counter", {
data: function() {
return {
count: 0}},template: `<button v-on:click="count++">You clicked me {{ count }} times.</button>`;
})
let vm = new Vue({
el: "#app"
})
Copy the code