简体   繁体   English

你如何在 Vue 中条件绑定 v-model?

[英]How do you conditional bind v-model in Vue?

In JavaScript, object can optional spread value like this:在 JavaScript 中,对象可以像这样可选地传播值:

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

In React, JSX can optional pass props like this:在 React 中,JSX 可以像这样可选地传递道具:

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

Now in Vue, how do I achieve optional v-model ?现在在 Vue 中,我如何实现可选的v-model

I have a textarea like this我有一个这样的 textarea

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

How can I achieve optional bind v-model ?如何实现可选的绑定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 )发生错误时, textarea 显示警告并清除输入( v-model

The correct way is to use the get and set properties of computed variable正确的方法是使用计算变量的get和set属性

<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>

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>

You need to use v-if to check first condition, if matched then bind model like this您需要使用v-if检查第一个条件,如果匹配,则像这样绑定模型

<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有关更多信息,请参阅此链接

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";
      }
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM