使用bus.js来进行组件中简单的通信

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Dj_Fairy/article/details/87269450

1、首先建立一个bus.js

2、在bus.js里面填上如下信息

import Vue from 'vue'

const bus = new VUe()
export default bus

3、在需要通信的组件中引入bus.js

import Bus from './bus.js'

4、组件通信

<template>
 </template> 

import Bus from './bus.js' 
export default { 
    data() {
        return {
            message: ''"
        }
     },
  methods: {
       bus () {
          Bus.$emit('msg', '我要传给兄弟组件们,你收到没有')
       }
    }
}

5、打开要和$emit通信的另外一个组件  添加

<template>
    <div id="on">
            <p>{{message}}</p>
    </div>
</template>

import Bus from './bus.js'
export default {
    data() {
      return {
        message:  ''
      }
    },
    mounted() {
    let self = this
       Bus.$on('msg', (e) => {
         self.message = e
     console.log(`传来的数据是:${e}`)
       })
     }
   }

猜你喜欢

转载自blog.csdn.net/Dj_Fairy/article/details/87269450
今日推荐