Search code examples
vuejs2

Vue JS component listens to grandchild component for event


There are notes in the Vue docs (https://v2.vuejs.org/v2/guide/components.html#Listening-to-Child-Components-Events) but would this apply to grandchildren as well?

grandchild.vue

   <select class="form-control" v-model="selected" @change="updateValue()" >
     ...
    </select>
  methods: {
    updateValue: function () {
      this.$emit('refreshModel', this.selected)
      this.$emit('input', this.selected)
      console.log('selected ' + this.selected + ' in ' + this.$props.field)
    }
  }

Grandparent.vue

<parent-form ...
              v-on:refresh-model="refreshModel"
             ...
</parent-form>

methods: {
  refreshModel: function (event) {
    console.log("Hello Vue JS");
  },

Obviously I have removed a lot of the code and hopefully just left the essentials.

The result of running this is the that the log statement in the grandchild is displayed but not the refreshModel function.

Can anyone see what I am doing wrong?

Regards


Solution

  • You need to 'daisy-chain' the events, so you would have to put a listener in the Parent-Form that re-emits the event to the Grandparent.

    Child(emit) -> Parent(listen, emit) -> Grandparent(listen)

    Vuex gets around this issue by using a 'state' as the single source of truth, so only the 'state' needs to be updated to reflect the changes in all connected components.

    https://vuex.vuejs.org/