The parameters in VUE are passed in the following ways
- Parent and child components are passed to each other via props, $emit
- Event Bus Indicates the event bus
- vuex
The first is limited to passing between parent and child components, using the Event Bus or VUEX to pass between sibling components. The implementation discussed here is the Event Bus.
Start by creating a simple SRC /router/index.js route
import Vue from 'vue'
import Router from 'vue-router'
import Posts from '@/components/posts.vue'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'HelloWorld',
component: HelloWorld,
children: [
{path: 'posts', component: Posts}
]
}
]
})
Copy the code
To facilitate observation, the above implementation of a nested pattern, the HelloWorld page nested the Posts page, we put a button in the HelloWorld page, click the button to send data, the posts page to receive data. Then create an event-bus.js file that will be used only to export the EventBus.
import Vue from 'Vue'
export const EventBus = new Vue()
Copy the code
Edit the SRC/components/HelloWorld. Vue
<template> <div id="example"> <button @click="sendMsg">send</button> <router-view></router-view> </div> </template> <script> import {EventBus} from '.. /event-bus' import posts from './posts.vue' export default { components: { posts, }, methods: { sendMsg () { EventBus.$emit('a-message', {name: 'kim', type: 'human'}) } } } </script> <style lang="css" scoped> </style>Copy the code
src/components/posts.vue
</div> <div class=""> {{MSG}} </div> </div> </template> <script> import {EventBus} from '.. /event-bus' export default { name: 'posts', data () { return { msg: '123' } }, mounted () { EventBus.$on('a-message', (msg) => { console.log('receive message', msg) this.msg = msg.name }) } } </script> <style lang="css" scoped> </style>Copy the code
The default MSG on the Posts page is 123, and when the button is clicked, it is updated to Kim
Remove the monitor
If you want to remove listening for events, you can do something like this:
EventBus.$off('a-message', {})
Copy the code
Or simply call eventBus.$off() to remove all event channels without adding any parameters.
$emit = this.$root.$on = this.$root.$on = this.
Event-bus.js must be introduced into each component whenever EventBus is used. In fact, there are other ways we can make things easier. Create a global EventBus.
Global EventBus
Create an EventBus in main.js and register it with Vue’s Prototype
var EventBus = new Vue()
Object.defineProperties(Vue.prototype, {
$bus: {
get: function () {
return EventBus
}
}
})
Copy the code
You can then use this.$bus just as you would this.$route
this.$bus.$emit('b-message','message from global bus')
this.$bus.$on('b-message', msg => {
console.log('b-message',msg)
})
Copy the code
For details, see Vue EventBus