Home > Web Front-end > JS Tutorial > body text

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

不言
Release: 2018-03-30 17:59:12
Original
2067 people have browsed it

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()
Copy after login

Introduce Bus.js into the components that need to communicate

import Bus from '../common/js/bus.js'
Copy after login

Add a button and $emit an event after clicking it

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

methods

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

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
       })
     }
   }
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template