Vue.js:如果语句为true,则设置复选框为选中状态 [英] Vue.js: Set checkboxes checked if statement is true

查看:237
本文介绍了Vue.js:如果语句为true,则设置复选框为选中状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在旧的车把视图中有以下复选框:

I had the following checkbox in my old handlebar view:

<div class="form-group">
    <input type='checkbox' name='xmlOnline[]' value="stepstone" class='' {{#if (ifIn 'stepstone' job.xmlOnline)}} checked="checked" {{/if}}> Stepstone
    <input type='checkbox' name='xmlOnline[]' value="karriere" class='' {{#if (ifIn 'karriere' job.xmlOnline)}} checked="checked" {{/if}}> Karriere
</div>

因此,如果job.xmlOnline具有"stepstone"作为值,则应将其标记为已选中". "karriere"也是如此.

So if job.xmlOnline has "stepstone" as value, it should mark it as checked. Same goes for "karriere".

现在,我正在尝试以POST形式在Vue.js中实现相同的目的. 这就是对象作业"的样子: http://t2w-api.herokuapp.com /jobs/590c20d42b1c4300046bb1b9

Now I am trying to achieve the same thing in Vue.js for my POST form. This is how the object "job" looks like: http://t2w-api.herokuapp.com/jobs/590c20d42b1c4300046bb1b9

因此它可以包含"karriere","stepstone",两者或"null".

So it can contain either "karriere", "stepstone", both or "null".

到目前为止,我在组件中得到了什么:

What I got so far in my component:

<div v-for="(xml, index) in job.xmlOnline">
    <input type="checkbox" :checked="xml == 'stepstone'"> Stepstone {{ index }}
    <input type="checkbox" :checked="xml == 'karriere'"> Karriere {{ index }}
</div>

复选框被选中,但是我重复了它们.我也不知道如何添加v模型.

Checkboxes get checked, but I have them duplicated. I also do not know how to add a v-model.

这是我组件的来源.做一些与资格"/责任"类似的事情:

This is the source of my component. Did something similiar with "qualifications"/"responsibility": https://github.com/markusdanek/t2w-vue/blob/mdanek/2-auth-system/src/components/backend/JobEdit.vue

推荐答案

可能的解决方案

<input type="checkbox" 
       :checked="job.xmlOnline && job.xmlOnline.includes('stepstone')"
       @change="onChange('stepstone', $event)"> Stepstone
<input type="checkbox" 
       :checked="job.xmlOnline && job.xmlOnline.includes('karriere')"
       @change="onChange('karriere', $event)"> Karriere

还有onChange方法

And the onChange method

methods:{
  onChange(value, $event){
    if (!this.job.xmlOnline)
      this.job.xmlOnline = []

    const index = this.job.xmlOnline.findIndex(v => v == value) 
    const checked = $event.target.checked

    if (checked && index < 0)
      this.job.xmlOnline.push(value)
    if (!checked && index >= 0)
      this.job.xmlOnline.splice(index, 1)
  }
}

示例.

这篇关于Vue.js:如果语句为true,则设置复选框为选中状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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