I have this v-select :
<v-select
multiple
v-model="group.structures"
:options="filter"
label="name"
@input="changed"
></v-select>
When I get the attribute of my function "changed", I got an array with all selected values when I add or remove an item from my v-select.
changed(value) {
console.log(value); // Return an array with all items in (group.structures).
}
I don't want to get all the array but only the selected/removed value. Is there any way to get the selected value?
Thanks.
CodePudding user response:
One of the ways to achieve what you want is store the previous value in variable then compare the new value with it
data() {
return {
previousSelectedStructures: [];
// ...
}
}
changed(value) {
let added = value.filter(
(val) => !this.previousSelectedStructures.includes(val)
);
let removed = this.previousSelectedStructures.filter(
(val) => !value.includes(val)
);
// Do some stuff
console.log(value);
this.previousSelectedStructures = value;
}
CodePudding user response:
Try like following snippet :
new Vue ({
el: '#demo',
vuetify: new Vuetify(),
data() {
return {
group: {
structures: []
},
filter: [1,2,3,4,5,6,7],
selected: []
}
},
methods: {
changed(value) {
let item = null
if(value.filter(val => !this.selected.includes(val)).length){
item = 'Added: ' value.filter(v => !this.selected.includes(v)).toString()
} else {
item = 'Removed: ' this.selected.filter(v => !value.includes(v)).toString()
}
this.selected = value;
console.log(item);
}
}
})
Vue.config.productionTip = false
Vue.config.devtools = false
<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">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui">
<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>
<div id="demo">
<v-app>
<v-select
multiple
v-model="group.structures"
:items="filter"
label="name"
@input="changed"
>
</v-select>
</v-app>
</div>
CodePudding user response:
Wow! It works! Thank you!
For those who have the same request, don't forget to fill your previousSelectedStructures up with the existing content :
created(){
this.previousSelectedStructures = this.group.structures;
},