The use Vue $ Bus

The use Vue $ Bus

The Bus pulled into a single file

Bus.js

import Vue from 'vue';
let Bus = new Vue();
export default Bus;

Create two brothers set up

C2.vue

<template>
    <view>
        <h1>c2</h1>
    </view>
</template>
<script>
// 引入Bus
import Bus from '@/util/Bus';
export default {
  // 在载入后的生命周期中
     mounted () {
            // 给bug绑定一个log事件,等待兄弟组件出发
        Bus.$on('log', content => {
          // 输出兄弟组件传递的内容
            console.log(content)
        });
    }    
}
</script>

C1.vue

<template>
    <view>
        <button @tap="tapBus">c1</button>
    </view>
</template>
<script>
import Bus from '@/util/Bus';

export default {
    methods:{
        tapBus(){
      // 点击按钮触发log事件,传递120过去,会输出到控制台
            Bus.$emit('log', 120)
        }
    }
}
</script>

index.vue


<template>
    <view class="content">
    <!-- 在首页显示这两个组件 -->
        <C1></C1>
        <C2></C2>
    </view>
</template>

<script>
// 引入组件
import C1 from '@/components/c1.vue';
import C2 from '@/components/c2.vue';
    export default {
    // 并注册
        components:{
            C1,
            C2
        },
    }
</script>

NOTE: This embodiment is introduced, after packing case webpack Bus local scope may occur, i.e., referring to two different Bus, normal communication can not cause

Bus injected into the prototype on the Vue

main.js

// 将挂载到prototype单独抽离成一个文件
import plugin from './util/Bus';
Vue.use(plugin);

./util/Bus.js

import Bus from 'vue';
let install = function (Vue) {
    // 设置eventBus
    Vue.prototype.bus = new Bus();
}

export default { install };

C2.vue

<template>
    <view>
        <h1>c2</h1>
    </view>
</template>
<script>
export default {
     mounted () {
    // 注册事件
        this.bus.$on('updateData', (content)=>{
            console.log(content);
        });
    },
    // 注册的总线事件要在组件销毁时卸载,否则会多次挂载,造成触发一次但多个响应的情况
    beforeDestroy () {
    this.bus.$off('updateData', (content)=>{
            console.log(content);
        });
  }
}
</script>

C1.vue

<template>
    <view>
        <button @tap="tapBus">c1</button>
    </view>
</template>
<script>
export default {
    methods:{
        tapBus(){
      // 触发兄弟组件身上的事件,并传一个object过去
            this.bus.$emit('updateData', {loading: false});
        }
    }
}
</script>

Both methods have been practiced in uni-app items too, there is a reference in the article to mount the root node in the method, but it does not fit into the small program, so there is no listed

Reference article: https: //www.cnblogs.com/fanlinqiang/p/7756566.html

Guess you like

Origin www.cnblogs.com/rope/p/12330490.html