John
John

Reputation: 1773

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

Upvotes: 3

Views: 3062

Answers (2)

As of Vue 2.4, there is a really simple way:

  1. The grandchild emits a signal just like before.

  2. In the middle generation, simply add v-on="$listeners" , to relay the signals upstream to its own parent. Example:

    <!-- Relays the signal from its child component to its own parent -->
    <vue-grandchild-component v-on="$listeners">  
    </vue-grandchild-component>
    
  3. In the grandparent (the final signal destination), catch the signal just like before.

For more details, including a code snippet you can run, see this thread

Upvotes: 4

Peter-M
Peter-M

Reputation: 145

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/

Upvotes: 0

Related Questions