zoukankan      html  css  js  c++  java
  • vue bus总线

    问题:解决兄弟组件通信的问题,当然你也可以选择vuex

    首先三个组件main.vue, child1.vue, child2,vue

    注意:注册的总线事件要在组件销毁时卸载,否则会多次挂载,造成触发一次但多个响应的情况

    方法一:使用一个空的Vue实例(bus.js)作为中央事件总线。

    bus.js
    import Vue from 'vue';
    const bus = new Vue();
    export default bus;
    main.vue
    <template>
      <div>
        <child1></child1>
        <child2></child2
      </div>
    </template>
    <script>
      export default {
        name: 'TestBaiDu',
        components: {
          child1: () => import("@/components/child1"),
          child2: () => import("@/components/child2")
        }
      }
    </script>
    child1.vue
    <template>
      <div>
        这是一个A组件
        <el-button type="primary" @click="clickEve">点击</el-button>
      </div>
    </template>
    
    <script>
    import bus from './bus'
    export default {
      data () {
        return {}
      },
      methods: {
        clickEve () {
          bus.$emit('getMessage', 'qqqq')
        }
      }
    }
    </script>
    child2.vue
    <template>
      <div>
        这是一个B组件
      </div>
    </template>
    
    <script>
    import bus from './bus'
    export default {
      data () {
        return {}
      },
    methods:{
    showMsg (msg) {
     
        console.log('msg', msg)
      }
      },
      created () {
        bus.$on('getMessage', this.showMsg ) 
      },
    beforDestory () {
      this.$off('getMessage', this.showMsg)
    }
    }

    </script>

    方法二:把bus定义在vue的prototype上,在全局都可以使用

    main.js中加入如下代码

    const bus = new Vue()

    Vue.prototype.$bus = bus

    这样我们就不需要再自己写bus.js引入了,就可以直接再组建中使用

    this.$bus.on(),this.$bus.$emit(),this.$bus.$off()

    方法三:使用插件vue-bus

    安装  npm install vue-bus --save

    main.js中引入   

    import VueBus from 'vue-bus';//中央事件总线

    Vue.use(VueBus)

    这样我们就不需要再自己写bus.js引入了,就可以直接再组建中使用

    this.$bus.on(),this.$bus.$emit(),this.$bus.$off()

     
     
  • 相关阅读:
    Unity The Method Signature Matching Rule
    Unity The Property Matching Rule
    Unity The Type Matching Rule
    Unity The Custom Attribute Matching Rule
    Unity The Member Name Matching Rule
    Unity No Policies
    Unity The Return Type Matching Rule
    Unity The Parameter Type Matching Rule
    Unity The Namespace Matching Rule
    关于TSQL递归查询的(转)
  • 原文地址:https://www.cnblogs.com/yangxiaoying/p/11532867.html
Copyright © 2011-2022 走看看