我观察到,当一个来自的普通属性data()
和一个派生自它的计算属性通过事件传递时,前者保持其反应性,而后者失去它。
我为它设置了以下测试用例(如果您愿意,也可以作为 JSFiddle):
const EventBus = new Vue();
Vue.component('comp', {
data() {
return {
arrData: ['a', 'b']
};
},
computed: {
arrComputed() {
return this.arrData.map((e) => e.toUpperCase());
}
},
template: `
<div>
<div>Original array: {{ arrData }}</div>
<div>Computed array: {{ arrComputed }}</div>
<button @click="remove('a')">Remove a</button>
<button @click="remove('b')">Remove b</button>
<button @click="pass">Pass through event</button>
<button @click="reset">Start over soft</button>
<button @click="resetHard">Start over hard</button>
</div>`,
methods: {
remove(name) {
name = name.toLowerCase();
if(this.arrData.indexOf(name) != -1) {
this.$delete(this.arrData, this.arrData.indexOf(name));
}
},
pass() {
EventBus.$emit('pass', this.arrData, this.arrComputed);
},
reset() {
this.$set(this.arrData, 0, 'a');
this.$set(this.arrData, 1, 'b');
},
resetHard() {
this.arrData = ['a','b'];
}
}
});
Vue.component('othercomp', {
data() {
return {
items1: [],
items2: []
}
},
mounted() {
EventBus.$on('pass', this.receive);
},
template: `
<div>
<div>Original array: {{items1}}</div>
<div>Computed array: {{items2}}</div>
</div>`,
methods: {
receive(items1, items2) {
this.items1 = items1;
this.items2 = items2;
}
}
});
var app = new Vue({
el: '#app',
components:['comp', 'othercomp']
})
<script src="//unpkg.com/vue@latest/dist/vue.js"></script>
<div id="app">
<comp></comp>
<othercomp></othercomp>
</div>
计算结果与正常属性有何不同,从而导致这种行为差异发生?
我从之前的问题中了解到,像这样传递反应对象是不好的做法,我应该使用 getter 函数,但是我仍然想知道为什么会出现这种差异。