Checkbox array in Vue Js
This behavior is well documented on the Checkbox binding Docs.
Here a little example emulating your logic
new Vue({ el: '#app', data: { user: { email: 'test@test.com', roles: [{id: 1, name: 'Client'}] }, roles: [ { id: 1, name: 'Client', }, { id: 2, name: 'Admin', }, { id: 3, name: 'Guest', } ] }})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script><div id="app"> <div> <label>Email</label> <input type="text" v-model="user.email" /> </div> <div v-for="role in roles" :key="role.id"> <label>{{role.name}}</label> <input type="checkbox" v-model="user.roles" :value="role"/> </div> <p>User's selected roels</p> {{user.roles}}</div>
We can use dynamic check box input rendering with the condition to select values from the customized function (in my example selectUsers
). In that function, we can write conditions that we need to compare before append to the selected array.
Demo:
This is the full NuxtJs(vue) component with dummy data.
<template> <v-container fluid> <p>{{selected }}</p> <div v-for="user in user_roles" :key="user[0]"> <input type="checkbox" @click="()=>{selectUsers(user[0])}" :value="user[0]" > {{user[1]}} </div> </v-container></template><script>import VueLodash from 'vue-lodash'import lodash from 'lodash'export default { data() { return { user_roles:[[1,"dd"],[2,"ddd"],[3,"kksse"],[4,"kske"]] , selected:[], }; }, methods: { selectUsers(id){ //in here you can check what ever condition before append to array. if(this.selected.includes(id)){ this.selected=_.without(this.selected,id) }else{ this.selected.push(id) } } }}</script>
<b-form-group v-for="resource, key in getSystem.user_roles" v-if="getSystem.user_roles" :key="key"> <label>{{resource.role_name}}</label> <input type="checkbox" v-model="userRoles" :value="resource.role_name" > </b-form-group><script> data(){ return { userRoles: [] } }</script>