我已经完成了这个小片段,你可以试试。
从长远来看,这里是代码:
<script type="text/x-template" id="app-template">
<v-app>
<v-container>
<v-select
v-model="selectedItems"
:items="options"
multiple
outline
offset-y
@change="(selection) => selectionChanged(selection)">
</v-select>
</v-container>
</v-app>
</script>
<div id="app"></div>
const App = {
template: '#app-template',
data: () => ({
selectedItems: [],
options: [
"One", "Two", "Three"
],
previousSelection: []
}),
methods: {
selectionChanged(selection) {
console.log('previous selection = ', this.previousSelection)
let selected = null
if (this.previousSelection.length < selection.length) {
selected = selection.filter(x => !this.previousSelection.includes(x))[0]
} else if (this.previousSelection.length > selection.length) {
selected = this.previousSelection.filter(x => !selection.includes(x))[0]
}
console.log('selected = ', selected)
this.previousSelection = selection
console.log('selection = ', selection)
}
}
}
new Vue({
vuetify: new Vuetify(),
render: h => h(App)
}).$mount('#app')
如果您跟踪先前的选择(我使用了previousSelection
变量)。您可以在当前选择和前一个选择之间进行区分,从而为您提供已单击的项目。
用这条线完成检查:
selected = selection.filter(x => !this.previousSelection.includes(x))[0]
对于取消选中,它执行相反的操作,它采用不在选择中但在前一个选择中的那个:
selected = this.previousSelection.filter(x => !selection.includes(x))[0]
这里[0]
是为您提供数组中唯一的项目,它是先前选择与当前选择之间差异的结果。
这可能不是最优雅的解决方案,但它适用于选中/取消选中。