senty
senty

Reputation: 12847

Triggering child method (or computed property) from root - vue2

In nested object, my computed property in my component doesn't track changes well, so computed property doesn't get triggered as expected. Instead, I want to trigger it in the from parent.

What is the proper way of executing a method, preferably this computed method from my root?

I tried using

this.$emit('updated'); on root method

this.$parent.$on('updated', this.organise); and catch it like this,

but this returns me an error:

Error in event handler for "updated": "TypeError: Cannot read property 'apply' of undefined"


Update:

Vue.prototype.globalEvents = new Vue();

var app = new Vue({
   el: '#root',
   methods: {
       x() {
          this.globalEvents.$emit('updated');
       }
   }
})

Vue.component('x', {
  created() {
     this.globalEvents.$on('updated', this.doStuff);
  }
})

Still giving me the same error

Upvotes: 0

Views: 588

Answers (1)

euvl
euvl

Reputation: 4786

The easiest way will be to create global event bus. You can do it this way:

Vue.prototype.globalEvents = new Vue();

And after that you will be able to emit and listen to events from anywhere in your component tree:

methods: {
 myMethod () {
    this.globalEvents.$emit(...)
    this.globalEvents.$on(...)
 }
}

Alternatively you can create local event bus the same way, for example, create module called bus.js:

import Vue from 'vue';

const events = new Vue();

export default { events };

And use it only in components where you want to use these events.

Upvotes: 2

Related Questions