Vuejs从$ on事件调用方法

时间:2017-04-11 13:05:02

标签: javascript events methods vuejs2

正在构建vuejs组件

methods: {
       filterPeople: function() {
        console.log('hello')
         //do some good stuff
       },


    },
    beforeCreate() {
     //do some ajax stuff

  },
    mounted() {
      Event.$on('applied', function() {
        console.log('the event is being caught')
        this.filterPeople();
      })
    })

我得到的错误是

this.filterPeople(); is not a function

当我将它移到Event.$on块之外时,它会调用该方法。

这是如何运作的?

2 个答案:

答案 0 :(得分:3)

这与Scope

有关
 var self = this;
      Event.$on('applied', function() {
         self.filterPeople();
})

答案 1 :(得分:1)

使用箭头功能保存上下文:

Event.$on('applied', () => this.filterPeople());