Home > Enterprise >  Vue 2. How get child value throuth v-model binding
Vue 2. How get child value throuth v-model binding

Time:09-27

I'm using v-model in custom component, but when I try to get the data(value props) of the child component in the parent component, then I get the old value, although the data in the parent has changed. If I get the data of the child component through setTimeout, then I get the data I need. How do I synchronize the v-model @input event and the data I receive from the child element in the parent?

This is the logic: there are AppForm(parent) component and AppSelect(child) component. I'm binding v-model on AddSelect, and I follow the changes through watch() { v-model-data }. Then v-model data has changed I call AppForm.data() method, which iterates through the list of children and gets the value prop of AppSelect component, but this value is old.

Short example: https://codesandbox.io/s/serene-wildflower-5seqx?file=/src/App.vue

CodePudding user response:

You're trying to get the child component's prop inside a watcher watching the data property that the prop is bounded to. Of course, the watcher triggers first, then the data is passed onto the child component and the prop is updated. Its not a good design if you are relying on the order that Vue events and functions are fired, but if you must, you can use vm.$nextTick() function to get values after everything is synced.

watch: {
    selectData(newV, oldV) {
      alert("Select data from parent component: "   newV);
      this.$refs.form.data();
      this.$nextTick(() => {
        alert("Show select data after 2sec");
        this.$refs.form.data();
      }, 2000);
    },
  },

Although, I'd suggest you shift the watcher inside the child component and access the data prop there.

  • Related