组件应使用独立的data对象

js对象是引用关系,所以如果return出的对象引用了外部的一个对象,那这个对象就是共享的,任何修改都会同步。比如:

 <div id="app">
    <my-component></my-component>
    <my-component></my-component>
    <my-component></my-component>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
<script>
    var data = {
        counter: 0
    }
    Vue.component('my-component', {
        template: '<button @click="counter++">{{ counter }}</button>',
        data: function () {
            return data;
        }
    })

    var app = new Vue({
        el: '#app'
    })
</script> 

以上并不是组件的期望结果,应该使用独立的data对象

 <div id="app">
    <my-component></my-component>
    <my-component></my-component>
    <my-component></my-component>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
<script>
    Vue.component('my-component',{
        template:'<button @click="counter++">{{ counter }}</button>',
        data:function(){ 
            return { 
                counter: 0
            }
        }
    })

    var app = new Vue({
        el:'#app'
    })
</script> 

You may also like...