[Vuejs]-Vue: Radio does not update its value when data changes asynchronously

1👍

The problem is the selected property in Radio.vue is only set equal to value in the created() hook. When the setTimeout() occurs in the parent component, Radio.vue‘s v-model property is changed, which updates its value property, but its selected property is not automatically updated to match.

The solution is to replace the created() hook change with a watcher on value that updates selected:

// Radio.vue
export default {
  created() {
    // ⛔️ Remove this
    //if (this.value) {
    //  this.selected = this.value
    //}
  },

  watch: {
    value: {
      handler(value) {
        this.selected = value
      },
      immediate: true,
    },
  },
}

demo

👤tony19

2👍

All you need is to change your function to an arrow function because it isn’t point your data like this

setTimeout(() => {
      this.type = "article";
      console.log(this.type);
}, 800);
👤Joseph

1👍

I assume your original code does not set the type in vue’s data function, so it will not reactive when you assign this.type to a new value.

Manage state in a form is complicated, check out this library: https://github.com/vue-formily/formily and maybe it helps you easier to work with form, it will let you separate the form definition from vue component that makes it reusable, and it will manage the state for you…

Here is a small demo for your problem: https://codepen.io/hqnan/pen/YzQbxxo

👤An Ha

Leave a comment