Vue.js: Set checkboxes checked if statement is true

谁说我不能喝 提交于 2020-01-13 03:24:32

问题


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>

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

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

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>

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


回答1:


A possible solution

<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

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

Example.




回答2:


You can just bind it to a literal as

:true-value="1" 

and it will work as expected.




回答3:


<b-form-checkbox class="col-sm-1 small" :value="1" switch v-model="user.nameb" :state="Boolean(user.nameb)" name="checkbox-validation">
    <b-form-invalid-feedback v-show="!Boolean(user.nameb)" :state="Boolean(user.nameb)">Not Verified</b-form-invalid-feedback>
    <b-form-valid-feedback v-show="Boolean(user.nameb)" :state="Boolean(user.nameb)">Verified</b-form-valid-feedback>
</b-form-checkbox>


来源:https://stackoverflow.com/questions/43982779/vue-js-set-checkboxes-checked-if-statement-is-true

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