Home  >  Article  >  Web Front-end  >  vue 2 uses Bus.js to implement non-parent-child component communication

vue 2 uses Bus.js to implement non-parent-child component communication

不言
不言Original
2018-03-30 17:59:122045browse

This article will share with you how to use Bus.js to implement non-parent-child component communication in vue 2. Friends in need can refer to it

$dispatch and $broadcast broadcast and broadcast are abandoned in vue2 Methods for dispatching events. Props and $emit() can be used in parent-child components. How to achieve communication between non-parent and child components can be achieved by instantiating a Vue instance Bus as a medium. Among the sibling components that want to communicate with each other, introduce Bus, and then implement communication and parameter transfer by calling Bus event triggering and monitoring respectively.
Bus.js can be like this

import Vue from 'vue'
export default new Vue()

Introduce Bus.js into the components that need to communicate

import Bus from '../common/js/bus.js'

Add a button and $emit an event after clicking it

<button @click="toBus">子组件传给兄弟组件</button>

methods

methods: {
    toBus () {
        Bus.$emit('on', '来自兄弟组件')
    }
  }

Another component also imports Bus.js and listens to the on event in the hook function

import Bus from '../common/js/bus.js'
export default {
    data() {
      return {
        message: ''
      }
    },
    mounted() {
       Bus.$on('on', (msg) => {
         this.message = msg
       })
     }
   }

Related recommendations:

vue 2.0 and elementUI implement breadcrumb navigation Column method code

Vue 2.5 Level E new feature sharing

Improvements related to TypeScript in Vue 2.5


The above is the detailed content of vue 2 uses Bus.js to implement non-parent-child component communication. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn