一. 使用方法
-
创建一个中间件文件,文件名自定义
这里创建的文件为
send.js
-
send.js
中配置
import Vue from 'vue' export default new Vue()
-
在
main.js
文件中引入中间件文件,并挂载挂载名自定义,这里为
$send
import send from './send.js' Vue.prototype.$send=send
-
组件中使用
$send
为main.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>