Vue高级进阶
事件总线(EventBus)
在非父子组件中是无法直接通信的,在vue中除了vuex可以统一管理状态,还有另外一种方法叫事件总线(EventBus),使用 EventBus 来作为沟通桥梁的概念,就像是所有组件共用相同的事件中心,可以向该中心注册发送事件或接收事件,所以组件都可以上下平行地通知其他组件。
eventBus.js文件
//创建eventBus.js文件
import Vue from 'vue'
export default new Vue;
全局引用
在main.js中导入eventBus.js,然后将它挂载到vue的原型上
import bus from './utils/eventBus'
Vue.prototype.bus = bus;
事件发送
this. b u s . bus. bus.emit(‘事件名’,参数)
this.bus.$emit("aMsg", '来自A页面的消息');
事件监听
this. b u s . bus. bus.on(‘事件名’,()=>{})
this.bus.$on("aMsg", ($event) => {
console.log($event,'$event')
});
注意
使用 b u s 要 在 d e s t r o y e d 生 命 周 期 函 数 中 使 用 bus要在destroyed生命周期函数中使用 bus要在destroyed生命周期函数中使用off销毁,要不然会叠加触发次数
beforeDestroy() {
//组件销毁前需要解绑事件。否则会出现重复触发事件的问题
this.bus.$off("aMsg");
},
混入(Mixin)
定义
混入 (mixin) 来分发 Vue 组件中的可复用功能。一个混入对象可以包含任意组件选项。当组件使用混入对象时,所有混入对象的选项将被“混合”进入该组件本身的选项。混入其实就是实现了单一继承和多重继承。
// 自定义一个混入对象
const myMixin = {
created () {
this.mixinFun()
},
methods: {
mixinFun () {
console.log('test use mixin!')
}
}
}
// 自定义当前使用混入对象的组件
const Example = Vue.extend({
mixins: [myMixin]
})
const example = new Example() // => "test use mixin!"
混入优先级
当混入对象跟组件定义同名时,以组件数据优先。
const mixin = {
data () {
return {
date: '21-09-18',
animal: 'dog'
}
}
}
new Vue({
mixins: [mixin],
data () {
return {
weather: 'sun',
animal: 'cat'
}
},
created () {
console.log(this.$data)
// => { animal: "cat", date: "21-09-18", weather: "sun" }
}
})
同名的钩子函数都将被调用,混入对象的钩子将在组件自身钩子之前调用。
const mixin = {
created () {
console.log('混入对象调用')
}
}
new Vue({
mixins: [mixin],
created () {
console.log('组件钩子调用')
}
})
// => "混入对象调用"
// => "组件钩子调用"
值为对象的选项,例如 methods、components 和 directives,将被合并为同一个对象。两个对象键名冲突时,取组件对象的键值对
const mixin = {
methods: {
foo () {
console.log('foo')
},
conflicting () {
console.log('from mixin')
}
}
}
const vm = new Vue({
mixins: [mixin],
methods: {
bar () {
console.log('bar')
},
conflicting () {
console.log('from self')
}
}
})
vm.foo() // => "foo"
vm.bar() // => "bar"
vm.conflicting() // => "from self"