简体   繁体   中英

Vuejs Update child component's data when parent updates prop sent to child

I have a parent component. It sends data in a prop to a child. That child also needs to update the value, so I followed this pattern :

The prop is used to pass in an initial value; the child component wants to use it as a local data property afterwards. In this case, it's best to define a local data property that uses the prop as its initial value.

You can see example code here: https://codesandbox.io/s/vue-template-gmh5n . You can see it running here: https://gmh5n.csb.app/ .

Problem

When I update the parent's data value, it updates the prop sent to the child (I can see that in Vue.js devtools). But the child's local data value is not updated.

Question

Is it possible to update the child's local data value when the prop sent by the parent is updated?

Here's how I would do it, https://codesandbox.io/s/vue-template-b2d8w

Instead of creating a data in child make it emit an event and update data in parent when event happens

You need to watch if initialCounter is changed from parent.

export default {
  name: "ChildWithProps",
  props: ["initialCounter"],
  data: function() {
    return {
      counter: this.initialCounter
    };
  },
  watch: {
    initialCounter(newInit) {
      this.counter = newInit;
    },
  }
};

Then If you want to update parent initialCounter in child, you need to pass function as prop to child.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM