在 v-model 中使用条件运算符? [英] Using conditional operators in v-model?

查看:143
本文介绍了在 v-model 中使用条件运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 vue 组件,它显示了一个表单,其中填充了要编辑的选定项目中的项目.现在我不想使用第二个表单来创建新项目.目前我使用 v-model 自动填充和更新项目,这显然更新了对象.我不能像这样使用条件运算符吗?

<div class="field"><label class="label">职位</label><p class="控制"><input type="text" class="input" placeholder="Job title" v-model="experiences[editIndex].title ?experiences[editIndex].title : ''"/></p>

</表单>

解决方案

v-model 可以使用条件运算符,但不能给 v-model像您在示例中尝试的字符串.

我不会使用相同的表单进行编辑和创建(可能是偏好).我会让表单成为它自己的组件,然后制作两个额外的表单组件用于编辑和创建.

然而,如果你真的想处理每个输入的 v-model 指令中的逻辑,你需要在三元运算符的最后部分给它一个变量.像这样:

v-model="experiences[i].title ?experience[i].title : newExperience.title"

I have a vue component that shows a form populated with items from a selected item to edit. Now I don't want to have to use a second form for creating a new item. At the moment I auto populate and update the item with v-model which obviously updates the object. Am I not able to use conditional operators in this like so?

<form @submit.prevent>
  <div class="field">
    <label class="label">Job Title</label>

    <p class="control">
      <input type="text" class="input" placeholder="Job title" v-model="experiences[editIndex].title ? experiences[editIndex].title : ''" />
    </p>
  </div>
</form>

解决方案

You can use conditional operators with v-model, but you can't give v-model a string like you're attempting in your example.

I wouldn't use the same form for editing and creating (might be preference). I would make the form its own component and then make two additional form components for editing and creating.

However, if you really want to handle the logic in each input's v-model directive, you would need to give it a variable in the last part of the ternary operator. Something like this:

v-model="experiences[i].title ? experiences[i].title : newExperience.title"

这篇关于在 v-model 中使用条件运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆