vue记录---$bus事件总线的使用

六、$bus事件总线的使用

1)配置事件总线
// src/main.js
new Vue({
  render: h => h(App),
  // 注册路由
  router,
  store,
  // 全局事件总线配置
  beforeCreate() {
    Vue.prototype.$bus = this
  },
}).$mount('#app')

2)使用
  • 发送
    <!-- src/components/Test/$busTest/EmitTest.vue -->
    <template>
      <div>
        <button @click="handleClick">清空OnTest组件中的message</button>
      </div>
    </template>
    
    <script>
      export default {
        name: "EmitTest",
        data() {
          return {
            newMessage: "新的message"
          }
        },
        methods: {
          handleClick() {
            // 发送不含参数参数
            // this.$bus.$emit('$busTest')
    
            // 发送含有参数
            this.$bus.$emit('$busTest', this.newMessage)
          }
        },
      }
    </script>
    
    <style lang="less" scoped>
    
    </style>
    
  • 接收
    <!-- src/components/Test/$busTest/OnTest.vue -->
    <template>
      <div>
        <h1>{{ message }}</h1>
      </div>
    </template>
    
    <script>
    export default {
      name: "OnTest",
      data() {
        return {
          message: "事件总线测试",
        };
      },
      mounted () {
        // 接受不含参数参数
        // this.$bus.$on("$busTest", () => {
        //   this.message = "不含参数"
        // })
    
        // 接受含有参数
        this.$bus.$on("$busTest", (newMessage) => {
          this.message = newMessage
        })
      },
    };
    </script>
    
    <style lang="less" scoped>
    </style>
    
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容