1👍
✅
This is a scoping issue. Adjust your mounted
hook as follows:
mounted() {
const self = this; // save pointer to current 'this'
bus.$on('idSelected', function(value) {
console.log('??? app10 click event value: ', value);
self.id = value; // use 'self' here
console.log('??? this.id', this.id);
});
}
Otherwise you loose a reference to current ‘this’, because it equals to ‘bus’ in your event listener. Try to console.log(this === bus)
inside your listener ( == true).
1👍
The value of this
is changing in your code inside your anonymous function. Use arrow function instead to keep the context of your vue instance.
var bus = new Vue();
Vue.component('component3', {
template: `
<div @click='change'>
{{id}}
</div>
`,
props: ['id'],
methods: {
change() {
console.log('??? component3 emit');
bus.$emit('idSelected', 3);
}
},
mounted() {
}
});
Vue.component('component4', {
template: `
<div>
{{id}}
</div>
`,
props: ['id'],
});
var app10 = new Vue({
el: '#app10',
data: function() {
return {
id: '?'
}
},
mounted() {
bus.$on('idSelected', (value) => {
console.log('??? app10 click event value: ', value);
this.id = value;
console.log('??? this.id', this.id);
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.js"></script>
<html>
<body>
<div id="app10">
<component3 :id="id"></component3>
<component4 :id="id"></component4>
</div>
</body>
</html>
Source:stackexchange.com