6

Is there any way to get computed data from child component to parent component? Because I'm sending the data from parent to child first and then I want to use the comuted property (data) in the parent component. I want to do that because I want to reuse that important component (child) in other components too.

I have a search input field for filtering my items, and when i wrote something down i wanna get back that list from the child component.

Parent component

<input class="form-control form-control-search m-input" autocomplete="off" type="text" v-on:input='testFunc()' v-model="search" placeholder="Search...">
<paginate-links v-if="items.length > 0" :models="items">
  <div class="m-list-timeline__item no-timeline" v-for="item in filterItems" v-bind:key="item.id">
    {{ item.title }}
  </div>
</paginate-links>

Child component

props: ['item']
computed: {
    filterItems () {
      return filter // here goes my code
    }
}

So can i get the filterItems in the parent component?

  • [Sending Messages To Parents With Events](https://vuejs.org/v2/guide/components.html#Sending-Messages-to-Parents-with-Events) – Daniel Beck May 18 '18 at 14:30
  • 3
    Possible duplicate of [Update parent model from child component Vue](https://stackoverflow.com/questions/41663010/update-parent-model-from-child-component-vue) – Daniel Beck May 18 '18 at 14:33
  • Can you clarify `comuted property (data)`? they're not the same. computed property is a reactive cached value that you can utilise a hook on, with data, you use `watch` to add hooks – Daniel May 18 '18 at 14:48
  • Sorry i meant just computed property. Because im getting something back with it right? Thats why I wrote data. –  May 18 '18 at 21:20

1 Answers1

7

There are a couple ways you can send data back to the parent, but probably the easiest way I'd say is using an emit within the computed.

in child:

computed:{
  myVal() {
    let temp = this.num + 1;
    this.$emit('onNumChange', temp);
    return temp;
  }
}

in parent template:

<my-child-component @onNumChange="changeHandler"/>

in parent script

methods: {
  changeHandler(value) {
    console.log('Value changed to: ', value);
  }
}

You could do a similar thing with watch, or pass a function from parent as a prop that notifies the parent, but my recommended way would be to use vuex

https://vuex.vuejs.org/en/

Daniel
  • 34,125
  • 17
  • 102
  • 150
  • That example you wrote i need to set that in the parent component or the child component? –  May 18 '18 at 21:21
  • also, as mentioned in the comments, the duplicate question pointed out has an answer with a working example https://codepen.io/CodinCat/pen/QdKKBa?editors=1010 – Daniel May 18 '18 at 21:53
  • I made it. Thanks a lot. :) –  May 18 '18 at 23:13