vue组件之间共享数据
- 父向子传值:v-bind属性绑定
- 子向父传值:v-on事件绑定
- 兄弟组件之间共享数据:EventBus
关于EventBus
初始化
新建一个eventbus.js的文件
import Vue from 'vue'
export const EventBus = new Vue()
使用
- 发送事件
import { EventBus } from "../event-bus.js";
EventBus.$emit("msg", 'msg');
- 接收事件
import { EventBus } from "../event-bus.js";
EventBus.$on("msg", (msg) => {
this.msg = msg;
});
创建全局EventBus
import Vue from "vue"
const EventBus = new Vue();
Object.defineProperties(Vue.prototype,{
$bus:{
get:function(){
return EventBus
}
}
})
// 在这个特定的总线中使用两个方法$on和$emit
// 一个用于创建发出的事件,它就是$emit;另一个用于订阅$on
var EventBus = new Vue();
this.$bus.$emit('nameOfEvent', { ... pass some event data ...});
this.$bus.$on('nameOfEvent',($event) => {
// ...
})