[Vuejs]-VueJS parent communication to child element

1👍

Maybe you could try passing a prop with .sync modifier to a child, and then in the child component you should use computed property. This is an option but I don’t know what are you trying to achieve, is there any specific reason that you must emit an event?

Read the vue.js dosumentation for props: https://v2.vuejs.org/v2/guide/components.html#Props

1👍

For what you are attempting, if possible, I’d use a Child Component ref and call a method on the child from the parent:

Vue.component('my-comp', {
  template: "#my-comp-template",
  props: ['name'],
  methods: {
    saveMyComp() {
      console.log('Saved:', this.name);
    }
  }
})

new Vue({
  el: '#app',
  data: {
    people: [{name: 'Bob'}, {name: 'Nelson'}, {name: 'Zed'}]
  },
  methods: {
    saveChild(index) {
      this.$refs.myComps[index].saveMyComp();
    }
  }
});
<script src="https://unpkg.com/vue@2.5.13/dist/vue.min.js"></script>

<div id="app">
  <div v-for="(person, index) in people">
    <button @click="saveChild(index)">saveMyComp</button>
    <my-comp :name="person.name" ref="myComps"></my-comp>
  </div>
</div>

<template id="my-comp-template">
    <span> {{ name }} </span>
</template>

Remember the parent is already coupled to the child component — since it knows it exists in the template declaration.

Leave a comment