vue基础之事件总线(非父子组件传值通信)

一、说明

事件总线其实就是一种非父子关系的通信方式

二、语法如下

(1)给vue的原型上挂载一个vue实例

Vue.prototype.bus = new Vue()

(2)发送事件,发送数据

  this.bus.$emit('事件名', 数据)

(3)监听事件,获取数据

 this.bus.$on('事件名', (数据) => {
                    //对数据进行操作
                })

三、案例代码

<!DOCTYPE html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
    <style>
        #root {
            display: flex;
            justify-content: space-around;
            width: 50%;
        }
    </style>
</head>

<body>
    <div id="root">
        <child-one></child-one>
        <child-two></child-two>
    </div>

    <script>
        //给vue的原型上挂载一个vue实例
        Vue.prototype.bus = new Vue()

        Vue.component('child-one', {
            template: `
我是child-one
是否收到two发来的的数据: 不是
`
, props: { data: { type: String } }, methods: { send() { this.bus.$emit('change2', 'one to two') } }, mounted() { this.bus.$on('change1', (data) => { this.data = data }) } }) Vue.component('child-two', { template: `
我是child-two
是否收到one发来的的数据: 不是
`
, props: { data: { type: String } }, methods: { send() { this.bus.$emit('change1', 'two to one') } }, mounted() { this.bus.$on('change2', (data) => { this.data = data }) } }) var vm = new Vue({ el: '#root', data: { }, }) </script> </body> </html>

四、结果图

vue基础之事件总线(非父子组件传值通信)_第1张图片

你可能感兴趣的:(vue基础)