Skip to content
Advertisement

How do you conditional bind v-model in Vue?

In JavaScript, object can optional spread value like this:

const payload = {
  name: "Joseph",
  ...(isMember && { credential: true })
};

In React, JSX can optional pass props like this:

<Child {...(editable && { editable: editableOpts })} />

Now in Vue, how do I achieve optional v-model?

I have a textarea like this

<template>
  <textarea v-model="textValue"> <!-- How can I optional bind v-model? -->
</template>

How can I achieve optional bind v-model?

I want to do this because I want to show warning on that textarea when error occurs.

When error occurs, textarea shows the warning and clear the input (the v-model)

Advertisement

Answer

The correct way is to use the get and set properties of computed variable

<template>
  <textarea v-model="compVal" />
</template>

<script>
export default {
  data () {
    return {
      valueTrue: 'hello',
      valueFalse: 'bye',
      selected: false
    }
  },
  computed: {
    compVal: {
      get () {
        if (this.selected) {
          return this.valueTrue
        } else {
          return this.valueFalse
        }
      },
      set (val) {
        if (this.selected) {
          this.valueTrue = val
        } else {
          this.valueFalse = val
        }
      }
    }
  }
}
</script>

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement