简体   繁体   中英

How to precheck VueJs3 checkboxes if their value is in an array at page creation while v-model used on the input?

I am trying to precheck some checkboxes based on their value: if the userApp.id is found in another array, I want the checkbox checked on page creation. The condition is no problem to me, yet I can't manage to precheck the checkboxes...

I use v-model to push the userApp.id in an array that will get in a POST body. I read in the VueJs documentation that v-model neutralizes the value and checked attributes.

How can I get those checkboxes already checked if they are in my other array? I tried to use JS with document.getElementById( ${userApp.id} ).checked = true, but it doesn't work.

view.vue

        <div v-for="userApp in userApps" :key="userApp">
            <div class="form-check">                
                <input class="form-check-input" type="checkbox" :value="userApp.id" :name="userApp.label" :id="userApp.id" v-model="checkedApps">
                <label class="form-check-label" :for="userApp.id">{{userApp.label}}</label>
            </div>
        </div>

With the data:

 data() {
    return {
         checkedApps: [],
    }

In fact, I did not think enough about the two-side binding created by the v-model. In the created() hook, I tried to push the id of the application I found in both arrays with a array.find():

this.userApps.forEach(userApp => {
    if(this.apps.find(item => item.id == userApp.appInstanceId)) {
      this.checkedApps.push(userApp.appInstanceId)
      console.log(this.checkedApps)
    }
  })

And job's done, My app checkbox (which id is in both arrays) is checked on page creation. and when unchecked is withdrawn from the checkedApps array. Hope it can help others.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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