eventbus封装

eventbus总结

封装

src/plugins/eventbus.js:

1
2
import Vue from 'vue';
export default new Vue();

src/plugins/index.js:

1
2
3
4
5
6
7
8
import eventbus from './eventbus';

export default {
install: (Vue, options) => {
// 挂载实例
Vue.prototype.$bus = eventbus;
}
};

使用

.vue文件中使用

手动触发

1
this.$bus.$emit('single-check', data);

其中,data为要传递的参数

监听

在create生命周期中监听并调用回调函数。

1
2
3
4
5
6
7
8
9
10
created() {
this.$bus.$off('check-handler').$on('check-handler', row => {
this.$router.push({
name: 'schoolContact',
query: {
schoolId: row.schoolId
}
});
});
}

js文件中使用

手动触发

需手动import

1
2
3
import bus from '@/plugins/eventbus';

bus.$emit('edit-handler', data);