Vue - 全局组件之间传值(Bus)

全局组件之间传值(Bus)

一. 传值方法

Bus:也可说是 总线机制、发布订阅模式、观察者模式

  1. main.js 中 new 一个 Vue 的实例,挂载在 bus 属性上

    Vue.prototype.bus=new Vue()
    

    在这里插入图片描述

  2. 传值组件

    通过 $emit 方法触发事件,同时携带内容

    methods: {
     handleClick(){
        this.bus.$emit('changeMsg','收到请回答')
      }
    },
    
  3. 接收值组件

    mounted 生命钩子中监听 bus 的改变,
    通过 $on 方法监听 bus 上的事件,接收传递回来的值。

    mounted() {
      var this_=this
      this.bus.$on('change',function(msg){
        console.log(msg)
      })
    },
    

二. 传值实例

传值组件

<template>
  <div>
    <button @click="sendMsg">传值</button>
  </div>
</template>

<script>
export default {
  data() {
    return {};
  },
  methods: {
    sendMsg() {
      this.bus.$emit("changeMsg", "收到请回答");
    }
  }
};
</script>

<style scoped>
</style>

接收值组件

<template>
  <div>
    <p>接收消息:{{ msg }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      msg: ""
    };
  },
  mounted() {
    var this_ = this;
    this.bus.$on("changeMsg", function(msg) {
      console.log(msg);
      this_.msg = msg;
    });
  }
};
</script>

<style scoped>
</style>
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值