一、 中央事件总线
1-1 举个栗子
1-1-1 代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>兄弟组件之间传值</title>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
</head>
<body>
<div id="root">
<student></student>
<hr>
<hr>
<hr>
<school></school>
</div>
<script>
const student = Vue.extend({
name: 'student',
template: `
<div>
<h2>学生</h2>
<h2>{{age}}</h2>
<button @click="sendDataToSch">发送数据给Student组件</button>
</div>
`,
data() {
return {
age: 20
}
},
methods: {
sendDataToSch() {
this.$bus.$emit('stuToSch', 666)
}
}
})
const school = Vue.extend({
name: 'school',
template: `
<div>
<h2>学校</h2>
<h2>{{address}}</h2>
</div>
`,
data() {
return {
address: '山西'
}
},
// 接收 student组件传来的数据
mounted() {
this.$bus.$on('stuToSch', (data) => {
console.log('我是School组件.我收到了数据', data); //接收的一方完成之后,最好解绑某一个事件
})
},
beforeDestory() {
this.$bus.$off("stuToSch");
},
})
new Vue({
el: '#root',
beforeCreate() {
Vue.prototype.$bus = this // 安装全局事件总线,$bus就是当前应用的vm
},
components: {
student,
school
},
})
</script>
</body>
</html>
1-1-2 展示结果
1-2 中央事件总线详细介绍
任意组件间通信
1-2-1
1-2-2
-
一种组件间通信的方式,适用于任意组件间通信。
-
安装全局事件总线:
new Vue({ ...... beforeCreate() { Vue.prototype.$bus = this //安装全局事件总线,$bus就是当前应用的vm }, ...... })
-
使用事件总线:
-
接收数据:A组件想接收数据,则在A组件中给$bus绑定自定义事件,事件的回调留在A组件自身。
methods(){ demo(data){......} } ...... mounted() { this.$bus.$on('xxxx',this.demo) }
-
提供数据:
this.$bus.$emit('xxxx',数据)
-
-
最好在beforeDestroy钩子中,用$off去解绑当前组件所用到的事件。
二、 消息订阅与发布
2-1 使用方式简介
-
-
一种组件间通信的方式,适用于任意组件间通信。
-
使用步骤:
-
安装pubsub:
npm i pubsub-js
-
引入:
import pubsub from 'pubsub-js'
-
接收数据:A组件想接收数据,则在A组件中订阅消息,订阅的回调留在A组件自身。
methods(){ demo(data){......} } ...... mounted() { this.pid = pubsub.subscribe('xxx',this.demo) //订阅消息 }
-
提供数据:
pubsub.publish('xxx',数据)
-
最好在beforeDestroy钩子中,用
PubSub.unsubscribe(pid)
去取消订阅。
-
-
2-2 案例展示
-
School.vue------》 接收数据方
<template> <div> <h2>学校地址:{{ address }}</h2> <h2 @click="showName">学校名称: {{ name }}</h2> </div> </template> <script> import pubsub from "pubsub-js"; // import mixin from "../mixin"; export default { data() { return { name: "哈哈哈", address: "地址", }; }, mounted() { this.pid = pubsub.subscribe("hello", function (e) { console.log("有人发布了hello消息,hello消息的回调执行了",e); }); }, beforeDestroy() { PubSub.unsubscribe(pid) } }; </script> <style> </style>
-
Student.vue------> 发送数据方
<template> <div> <h2 @click="showName">学生名称: {{ name }}</h2> <h2>学生住址: {{ address }}</h2> <button @click="sendStudentName">把学生名给School组件</button> </div> </template> <script> import PubSub from "pubsub-js"; // import mixin from "../mixin"; export default { data() { return { msg: "欢迎学习Vue!", }; }, mounted() {}, methods: { sendStudentName() { PubSub.publish("hello", 888); }, }, props: ["name", "address"], }; </script> <style> </style>