I am using Vue2 and Vuetify2. I have some checkboxes created using a v-for
loop. All checkboxes are inside a dialog component.
The Procedure-
- Before opening the dialog, I make an API request and fetch the items. Then, I open the dialog and select the checkboxes.
- Before closing the dialog, I empty the
selected
array, so I will have no items selected on opening the dialog again.
The issue-
When I open the dialog a second time, all checkboxes are already selected even though the variable selected
is set to an empty array []
. Then if I try to unselect any item, all are unselecting together and after that only one at a time is selectable.
Here is the working demo of this issue-
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/@mdi/[email protected]/css/materialdesignicons.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.min.css" rel="stylesheet">
</head>
<body>
<div id="app">
<v-app>
<v-btn dark @click.stop="onBeforeOpen">
Open Dialog
</v-btn>
<div >{{ msg }}</div>
<div >Selected items - {{ selected }}</div>
<v-dialog v-model="dialog" persistent>
<v-card >
<div><b>Select items and close dialog.</b></div>
<v-checkbox
v-for="item in items"
:key="item.id"
v-model="selected"
:value="item"
>
<template v-slot:label>
<v-card flat>
<div>{{ item.name }}</div>
<div>{{ item.email }}</div>
</v-card>
</template>
</v-checkbox>
<div align="center">
<v-btn color="error" small @click="onBeforeClose"
>Close Dialog</v-btn
>
</div>
</v-card>
</v-dialog>
</v-app>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.js"></script>
<script>
new Vue({
el: '#app',
vuetify: new Vuetify(),
data () {
return {
dialog: false,
selected: [],
items: null,
msg: null,
}
},
methods: {
onBeforeOpen() {
this.msg = "Fetching items from API....";
$.ajax("https://gorest.co.in/public/v2/users", {
success: (data, status, xhr) => {
this.items = data.splice(0, 2);
this.msg = null;
this.dialog = true
},
});
},
onBeforeClose() {
this.selected = [];
this.dialog = false;
}
}
})
</script>
</body>
</html>
EDIT-
If I use :value="item.id"
, the checkboxes are working fine. But I need to return the whole item object, not only the id, so I have to use :value="item"
.
CodePudding user response:
Sound like a bug... The first time the check box is displayed, it work fine... but the second time, it act like the v-model has a object (not array) and has the simple selection behavior.
You can force the multiple behavior with the prop multiple :
<v-checkbox
v-for="item in items"
:key="item.id"
v-model="selected"
:value="item"
multiple
>