Am very new to vue js and need a way where I have multiple checkboxes and when I select them an array gets updated with the checked elements with Vue JS. Eg :
allcolors = ['Red', 'Blue', 'Green'];
and I select first two so my
selectedColors = ['Red', 'Blue'];
and then click saves, saves it to database.
When I open the form Red and Blue gets checked fetching record from database.
fetchedColors = ['Red', 'Blue'];
new Vue({ el: "#app", data: { items: [ { label: 'Red', value: 'red' }, { label: 'Blue', value: 'blue' }, { label: 'Green', value: 'green' }, ], checkedValues: [], }, })
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <label v-for="(item, index) in items" :key="index" > {{ item.label }} <input type="checkbox" :value="item.value" v-model="checkedValues" /> </label> {{ checkedValues }} </div>
Not really sure what you're asking. Do you mean something like this? Check the docs they may help - https://v2.vuejs.org/v2/guide/forms.html#Checkbox
new Vue({ el: "#app", data: { items: [ { label: 'Red', checked: true }, { label: 'Blue', checked: true }, { label: 'Green', checked: false }, ], }, })
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <label v-for="(item, index) in items" :key="index" > {{ item.label }} <input type="checkbox" :checked="item.checked" @change="({ target: { checked }}) => items[index].checked = checked" /> </label> </div>
If you want to show checkboxes that are checked when the form displays you could do something like this.
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.