I observed that when a normal property that came from data() and a computed property that is derived from it are passed through an event, the former keeps its reactivity while the latter loses it.
I set up the following test case for it (also as a JSFiddle if you prefer that):
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>
How is a computed different from a normal property so that this difference in behaviour occurs?
I learned from a previous question that passing reactive objects around like this is bad practice and that I should use a getter function instead, however I'd still like to know why this difference occurs.