Search code examples
vue.jscomputed-properties

retrieve a computed property in VueJS


I use Vue-Dragula to drap and drop. When I drop, it triggers the method:

mounted: function () {
    this.$nextTick(function () {
        Vue.vueDragula.eventBus.$on(
            'drop',
            function (args) {
                console.log(this.championship);
            }
        );

}

Now this.championship is a computed property:

computed: {
    championship(){
        return this.championships.find((elem) => elem.championship == this.championship_id);
    },
}

where championships and championship_id are global datas.

and console.log(this.championship); returns undefined

Now, I simplify, and I write:

computed: {
    championship(){
        return 2;
    },
}

and console.log(this.championship); keep returning undefined

What is wrong with my code???


Solution

  • this isn't referring to the Vue instance anymore in the drop event function. Try setting a reference to this in the mounted function before the $nextTick call:

    mounted: function () {
      let vm = this;
      this.$nextTick(function () {
        Vue.vueDragula.eventBus.$on(
          'drop',
          function (args) {
            console.log(vm.championship);
          }
        );
      }
    }