Using conditional operators in v-model?

淺唱寂寞╮ 提交于 2020-01-03 08:14:10

问题


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>

回答1:


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"



回答2:


If you use eslint-plugin-vue it will complain about ternary in v-model.

ESLint: 'v-model' directives require the attribute value which is valid as LHS. (vue/valid-v-model)

So I'd rather explicitly use pair of :value and @input props.

Like that:

<input 
  type="text" 
  class="input" 
  placeholder="Job title" 
  :value="experiences[editIndex].title ? experiences[editIndex].title : ''"
  @input="experiences[editIndex].title = $event.target.value"
/>

Also you can use some function for @input, which will check property existence and add it if necessary.



来源:https://stackoverflow.com/questions/44431507/using-conditional-operators-in-v-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!