force update computed properties in vuejs

2019-08-18 14:26发布

问题:

I've a Vuejs component that takes a "datasetId" as prop. I want a 2 way binding in my case, so I use the .sync modifier

<mycomponent :datasetid.sync=1 />

In this component I've a select component and I want it to show the good dataset, so I bind it to my props.

<select-component v-model="datasetid" />

Since we cannot mutate a prop (datasetid is a prop and bind it to v-model will potentially mutate datasetid). I decided to wrap this value on a computed property.

<select-component v-model="computedDatasetid">


computed: {
  computedDatasetid: {
    get() {
      return this.datasetid; // return the prop
    },
    set(v) {
      // don't mutate the prop directly but update the parent component.
      this.$emit('update:datasetid', v);
    }
  }
}

With this code, the "getter" is only called 1 time (when the component is create the first time). It's logical because the documentation says that the computed property is updated when an inner data is updated. And I don't update anything in the "setter".

How to force model to change when I call the setter ? (ex: this.computedDadasetid = 5)

Computed properties are the good way to do what I want ? Would be better to use raw 'data' or watcher or anything else ?

Thanks