I am using Vue2 and would like to have a selected-item component that can be reused. It will have a reference to an item that could send a msg on an event bus to set the item to null. This is also my first time working with Vue not in a single-file-compnent / vue file scenario.
I have the following code and have commented the problematic line:
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 am I doing wrong? Is there a better way to do this?
edit #1
it looks like setting the selectedApp to capture inline the emitted event works! Also removed the bus and some extraneous code. Like so:
<selected-item @remove="selectedApp = null" :item="selectedApp"></selected-item>