vue二十二:vue基础之事件总线实现非父子通信

 

事件总线工作原理

在代码中实现

创建非父子关系的组件

 

创建中央事件总线(空的vue实例)

 

mounted生命周期函数,在当前组件的dom创建完后就会调用

在mounted生命周期中绑定订阅事件总线

绑定发布事件总线

获取发布的状态

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="vue.js"></script>
</head>
<body>
<div id="app">
<author></author>
<user></user>
</div>

<script>
var bus = new Vue() // 空Vue实例,就是中央事件总线

Vue.component('author', {
template: `
<div style="background: blue">
公众号作者
<input type="text" ref="inputText">
<button @click="handleClick()">发布文章</button>
</div>`,
methods:{
handleClick(){
bus.$emit('msg', this.$refs.inputText.value)
}
}
})
Vue.component('user', {
template: `
<div style="background: green">
微信用户
</div>`,
mounted() { // 生命周期函数,在当前组件的dom创建完后就会调用
bus.$on('msg', (data) => {
console.log('收到推送了', data)
})
console.log('生命周期函数,在当前组件的dom创建完后就会调用')
}
})


new Vue({
el: "#app",
})

</script>
</body>
</html>

 

posted @ 2021-01-19 21:55  向前走。  阅读(115)  评论(0编辑  收藏  举报