0

Is it possible to use two-way computed properties with vuejs when using class-style components? In my case, given an app with a simple vuex store, is there a way to bind the store values to a select with v-model?

In the vuex documentation there is an example for two-way binding:

// ...
computed: {
  message: {
    get () {
      return this.$store.state.obj.message
    },
    set (value) {
      this.$store.commit('updateMessage', value)
    }
  }
}

But I did not get this to work with class components. I tried something like

private get myvalue(): boolean {
  return store.state.myvalue;
}

/* Same type of function I would use when using @input one-way binding*/
private set myvalue(e: Event /* Wrong type for the setter... */) {
  const target: HTMLSelectElement = e.target as HTMLSelectElement;
  const value = target.value;

  if (Boolean(value)) {
    store.commit("myvalue", target.value);
  }
}

But this obviously does not work because getters/setters always have the same data type. The type of myvalue is bool, but passing it to both functions does not work as well, because when binding to a select like so

<select v-model="myvalue">
  <option value="false">No</option>
  <option value="true">Yes</option>
</select>

The setter does not seem to get a value.

I also tried to bind the value to the select manually (like you would do with text-inputs) but using :selected on the select options didn't work (the first option always was selected).

2
  • If myvalue is a bool then maybe you need to make sure the option values are also bools instead of strings by doing :value="false" and :value="true". Commented Jul 2, 2019 at 12:52
  • @DecadeMoon I'll look into that. I checked for that when testing if an option was selected but not when setting the value. Thanks for that hint. Commented Jul 2, 2019 at 12:53

1 Answer 1

1

I got it working after a little while. Just using class setters and getters was the solution afterall:

<select v-model="myvalue">
  <option :value="false">No</option>
  <option :value="true">Yes</option>
</select>

and

private get myvalue(): boolean {
  return store.state.myvalue;
}

private set myvalue(value: boolean) {
  store.commit("myvalue", value);
}

work for the basic functionality.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.