<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>vue</title>
<script src="../vue.js"></script>
</head>
<body>
<div id="main">
<send></send>
<receive></receive>
</div>
<script>
<!--消息总线,其实就是一个Vue对象-->
var bus = new Vue();
<!--发送组件-->
Vue.component('send',{
template:`
<div>
<input type="text" v-model="sendText">
<button @click="send">发送</button>
</div>
`,
data() {
return {
sendText: ''
}
},
methods: {
send() {
bus.$emit('channel1',this.sendText);
}
}
});
<!--接收组件-->
Vue.component('receive',{
template:`
<div>
这里是接收组件接收到的文本:{{receiveText}}
</div>
`,
data() {
return {
receiveText: ''
}
},
// 初始化的时候就订阅消息
mounted() {
bus.$on('channel1',(msg) => {
this.receiveText = msg;
})
},
methods: {
}
});
new Vue({
el: '#main',
data: {
},
methods: {
}
})
</script>
</body>
</html>
利用消息总线实现非父子组件的通信
最新推荐文章于 2021-03-13 16:55:57 发布