Vue封装on emit等方法

Vue中组件之间相互通信可考虑用on emit方法,而这两个方法使用时需要在同一个实例vue来调用才起作用,以下代码描述的就是用一个vue实例封装常用的方法并赋值给全局的变量,以便在任何一个组件都可调用这些方法

/assets/js/event.js

import Vue from 'vue';

const eventHub = new Vue({
    methods: {
        /* eslint-disable prefer-spread */
        on(...args) {
            this.$on.apply(this, args);
        },
        emit(...args) {
            this.$emit.apply(this, args);
        },
        off(...args) {
            this.$off.apply(this, args);
        },
        once(...args) {
            this.$once.apply(this, args);
        },
        /* eslint-disable prefer-spread */
    },
});
export const eventBusPlugin = (V) => Object.defineProperty(V.prototype, '$event', {value: eventHub, writable: true});

export default eventHub;

main.js 引用封装的event

import Vue from 'vue';
import {eventBusPlugin} from '/assets/js/event';
Vue.use(eventBusPlugin);//使用封装的event.js
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
});

在页面使用封装的event

mounted(){
    this.$event.on('change_value',id);
    this.$event.emit('change_value',1);
    ...
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 绿野繁茂的丛林 与插遍枝头的花朵 请别挡住我更正渴慕的灵魂 白色最为单纯 或者最为肤浅 黑色最为深邃 或者最为阴毒...
    小脚丫头片子阅读 341评论 2 23
  • 求职面试过程中,面试官问完自己关心的问题后,通常会对求职者说:“你还有什么问题想问我吗?”对于这个环节,网络上有很...
    呆小鱼向上游阅读 439评论 0 0
  • 一开始用这个App是被它的名字吸引—“简书”,简单写点东西。下载好,迫不及待的想写点什么却发现无从下笔。软件的首...
    宫鸡少油阅读 277评论 0 0

友情链接更多精彩内容