VueJS侦听组件内部的外部事件

时间:2020-06-19 12:15:11

标签: vue.js nuxt.js

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

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在组件具有已安装?

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

带有箭头功能的变体

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;
    },
  }
}