Joseph
Joseph

Reputation: 4685

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)

Upvotes: 7

Views: 28137

Answers (4)

Harsh Patel
Harsh Patel

Reputation: 6820

You need to use v-if to check first condition, if matched then bind model like this

<template>
  <textarea v-if="something" :value="textValue">
  <textarea v-else v-model="textValue"> <!--  bind v-model here -->
</template>

Or you can use ternary operator like this

<textarea v-model="textValue == 'test' ? 'ifTrue' : 'ifFalse'">

For more refer this links

Upvotes: 1

Dicren
Dicren

Reputation: 583

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>

Upvotes: 16

Ilijanovic
Ilijanovic

Reputation: 14904

Didnt you try the ternary operator?

<template>
  <textarea v-model="someValue == 'test' ? 'value1' : 'value2'">
</template>

and in data:

data(){
   return {
      someValue: "test",
      value1: "i am value 1",
      value2: "i am value 2"
   }
}

Or you can do it with computed properties like this:

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

computed: {
   myModel(){
      if(this.someValue == "test"){
         return "value1";
      }else{
         return "value2";
      }
   }
}

Upvotes: -3

TedMeftah
TedMeftah

Reputation: 1915

I think something like this would do the trick for you

<template>
  <textarea v-if="hasError" :value="textValue">
  <textarea v-else v-model="textValue">
</template>

Upvotes: 2

Related Questions