Implementation of non parent-child component communication through Bus mechanism
1. Create an empty instance (Bus central event Bus can also be called intermediate component)
2. Use $emit $on to trigger and listen to events to realize the communication between non parent and child components
Before using this.$bus.$on to transfer values between components, this.$bus.$off event needs to be logged out
Namely:
this.$bus.$off('hiHeader').$on('hiHeader', (val) => {
this.sending = val
})
See: Before using this.$bus.$on to transfer values between components, this.$bus.$off event needs to be logged out
I. by this.$bus.$on()
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <script type="text/javascript" src="vue.js"></script> <div id="app"></div> <script type="text/javascript"> // Define communication middleware Vue.prototype.$bus = new Vue() var myHeader = { template: ` <div>I am the head.|{{sending}} </div> `, data() { return { sending: '' } }, created() { // Unbound before binding to prevent multi component click failure // Here this.$bus.$on monitors the middleware to obtain data this.$bus.$off('hiHeader').$on('hiHeader', (val) => { this.sending = val }) } } var myFoot = { template: ` <div>I am foot. <button @click="sendToHeader">Send a message to the head</button> </div> `, methods: { sendToHeader() { // Trigger the hiHeader event to pass data this.$bus.$emit('hiHeader', 'My head is not made of dough') } } } new Vue({ el: '#app', components: { myHeader, myFoot }, template: ` <div> <myHeader></myHeader> <myFoot></myFoot> </div> ` }) </script> </body> </html>
II. Redirect through this
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <script type="text/javascript" src="vue.js"></script> <div id="app"></div> <script type="text/javascript"> // Define communication middleware Vue.prototype.$bus = new Vue() var myHeader = { template: ` <div>I am the head.|{{sending}} </div> `, data() { return { sending: '' } }, created() { // Redirect this var transfer = this // transfer.$bus.$off('hiHeader').$on('hiHeader', function (val) { // transfer.sending = val // }) transfer.$bus.$on('hiHeader', (val)=>{ transfer.sending = val }) } } var myFoot = { template: ` <div>I am foot. <button @click="sendToHeader">Send a message to the head</button> </div> `, methods: { sendToHeader() { // Trigger the hiHeader event to pass data this.$bus.$emit('hiHeader', 'My head is not made of dough') } } } new Vue({ el: '#app', components: { myHeader, myFoot }, template: ` <div> <myHeader></myHeader> <myFoot></myFoot> </div> ` }) </script> </body> </html>