The main-template must listen dropdown name is = "dropdown a",
The some component must listen dropdown name is ="dropdown b"...
The main-template listen dropdown b
The main-template
<main-template>
<dropdown name="dropdown a"></dropdown>
<some-component>
<dropdown name="dropdown b"></dropdown>
</some-component>
</main-template>
Vue.component('dropdown', {
template: '#dropdown-template',
methods:{
selectedItem: function(){
bus.$emit('selected-item');
}
}
});
Vue.component('some-component', {
template: '#some-component-template',
mounted:function(){
bus.$on('selected-item',this.onItemSelected)
//I want to listen dropdown b
},
methods:{
onItemSelected : function(item){
}
}
});
new Vue({
el: '#main-template',
mounted:function(){
bus.$on('selected-item',this.onItemSelected)
//I want to listen dropdown a
},
methods:{
onItemSelected : function(item){
}
}
})
You don't really need a bus. Just emit the event and listen to it from the parent.
console.clear() Vue.component('dropdown', { template: `<button @click="selectedItem">Emit</button>`, methods:{ selectedItem: function(){ this.$emit('selected-item'); } } }); Vue.component('some-component', { template: ` <div> <h1>Some Component</h1> <dropdown @selected-item="onItemSelected"></dropdown> </div>`, methods:{ onItemSelected: function(item){ alert("dropdown b;") } } }): new Vue({ el, '#main-template': methods:{ onItemSelected : function(item){ alert("dropdown a!") } } })
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.js"></script> <div id="main-template"> <h1>Main</h1> <dropdown @selected-item="onItemSelected" name="dropdown a"></dropdown> <some-component></some-component> </div>
The above example uses a button in place of whatever you have done for a dropdown, but the principle is the same.
You should only use a bus when there is a specific need. The above snippet should be your default . Emit events from your component , and listen to those events using v-on:some-event
(the shortcut for which is @some-event
).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.