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

Vue项目中全局组件之间传值(中间件传值)

一. 使用方法

  1. 创建一个中间件文件,文件名自定义

    这里创建的文件为 send.js

    在这里插入图片描述

  2. send.js 中配置
    在这里插入图片描述

    import Vue from 'vue'
    export default new Vue()
    
  3. main.js文件中引入中间件文件,并挂载

    挂载名自定义,这里为$send

    import send from './send.js'
    Vue.prototype.$send=send
    
  4. 组件中使用

    $sendmain.js中的挂载名
    sendMsg为传递、接收的通信名
    一组传递、接收的通信,需保持通信名相同
    多组传递、接收的通信,需保持每组通信的通信名唯一

    传递值

    this.$send.$emit('sendMsg',"需要传的数据")
    

    接收值

    mounted() {
      // mounted 生命周期钩子中获取
      this.$send.$on("sendMsg", res => {
        console.log(res);
      });
    },
    

二. 传值实例

传值组件

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

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

<style scoped>
</style>

接收值组件

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

<script>
export default {
  data() {
    return {
      msg: ""
    };
  },
  mounted() {
    this.$send.$on("sendText", res => {
      console.log(res);
      this.msg = res;
    });
  }
};
</script>

<style scoped>
</style>
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值