Vue 2 simple Case for brother (non-parent) component communication using Bus.js

Source: Internet
Author: User
Tags emit

$dispatch and $broadcast broadcast and distribute events are deprecated in vue2. Props and $emit () can be used in parent-child components. How to implement communication between non-parent and child components, through instance a Vue instance bus as the medium, to communicate with the sibling components, all introduced bus, and then by invoking bus event triggering and monitoring to achieve communication between components and parameter transfer.

First you need to add a bus.js anywhere

Write the following message inside the Bus.js

1 Import vue from ' Vue ' 2 export default new Vue;

Bus.js is introduced into the components that require communication

If your bus.js is a custom bus file, then the from behind will be changed to your place.

1 import Bus from './bus.js '

The next step is to communicate the components.

Add a trigger #emit的事件按钮

<template>    <div id= "emit" >
        <button @click = "Bus" > button </button>
    </div>




Data () {
return {
Message: ' "
}
},
Export Default {
Methods: { bus () { bus. $emit (' msg ', ' I'm going to pass it to the brother component, you received no ') } }
}
}

Open another component that you want to communicate with $emit add

Listen for MSG events in the hook function

<template>    <div id= "on" >            <p>{{message}}</p>    </div></template> Import Bus from './bus.js ' export default {    data () {      return {        message: ' '      }    },    mounted () {       Bus. $on (' msg ', (e) = = {         This.message = msg       })}   }

The last P will show the message from $emit.

Vue 2 simple Case for brother (non-parent) component communication using Bus.js

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.