I'm delving into Vue2 and hoping to create a reusable selected-item component. My goal is to have this component reference an item that can trigger a message on an event bus to reset the item to null. This marks my first experience working with Vue not in a single-file-component / .vue file setup.
Below is the code snippet where I've encountered some issues:
var bus = new Vue()
Vue.component('selected-item', {
props: ['item'],
methods: {
setToNull(item){
bus.$emit('setToNull', item);
}
},
template: `<span>
<div class="button round btn-app-class selected-btn">{{item.name}}<sup><span class='btn-delete link' @click="setToNull(item)">x</span></sup></div>
</span>
`
})
var vm = new Vue({
template:`
<div>
<div v-if="selectedApp">
<selected-item :item="selectedApp"></selected-item>
</div>
<div v-else>
no app selected
</div>
</div>
`,
data(){
return {
selectedApp: {id: 1, name: 'here is my name'}
}
},
mounted(){
bus.$on('setToNull', function (item) {
alert('within setToNull for: ' + item.name); // this works and outputs here is my name
item = null; // this doesn't work
})
}
})
What could be causing this issue? Is there a more efficient approach to achieving this functionality?
edit #1
It seems like directly setting selectedApp within the emitted event is effective! I've also cleaned up the code by removing the event bus and extraneous parts. Here's the updated implementation:
<selected-item @remove="selectedApp = null" :item="selectedApp"></selected-item>