首页 > 解决方案 > VueJS 监听组件内部的外部事件

问题描述

我有一个自定义对讲启动器按钮组件,如下所示:

export default {
  data  : function() {
    return ({
        open        : false,
        notif_count : 0,
    })
  },
  mounted           : function() {
    if (typeof Intercom !== 'undefined') {
        Intercom('onUnreadCountChange', function(count) {
            if (count) this.notif_count = count;
        });
        Intercom('onHide', function() {
            this.open = false;
        });
    }
  },
  computed      : {
    ...mapState({
        HIGHER  : (state) => state.intercom.higher,
    })
  },
}

显然该onHide方法在这里不正确,如果在组件安装后触发,我listen该如何更改它this.open的值?onHide

感谢您的帮助!

标签: vue.jsnuxt.js

解决方案


带有箭头功能的变体

export default 
{
  data() 
  {
    return {
        open        : false,
        notif_count : 0,
    };
  },
  mounted() 
  {
    if (typeof Intercom !== 'undefined') 
    {
        Intercom('onUnreadCountChange', (count) =>
        {
            if (count) this.notif_count = count;
        });
        Intercom('onHide', () =>
        {
            this.open = false;
        });
    }
  },
  computed: 
  {
    ...mapState({
        HIGHER  : (state) => state.intercom.higher,
    }),
  },
}

带有组件方法的变体

export default 
{
  data() 
  {
    return {
        open        : false,
        notif_count : 0,
    };
  },
  mounted() 
  {
    if (typeof Intercom !== 'undefined') 
    {
        Intercom('onUnreadCountChange', this.onUnreadCountChange);
        Intercom('onHide', this.onHide);
    }
  },
  computed: 
  {
    ...mapState({
        HIGHER  : (state) => state.intercom.higher,
    }),
  },
  methods:
  {
    onUnreadCountChange(count)
    {
            if (count) this.notif_count = count;
    },
    onHide()
    {
            this.open = false;
    },
  }
}

推荐阅读