问题描述
我正在使用 Vuetify 1.5.2 开发 vue.js 应用程序。我们有一个像这样的 v-select:
<v-select
v-model="selectedOptions"
:items="options"
multiple
outline
offset-y
small-chips
@change="(selection) => selectionChanged(selection)" >
</v-select>
...
...
selectionChanged(selection) {
console.log('selection=',selection);
}
我正在尝试将所选选项传递给处理程序,但我没有获得我选择的特定项目,而是获得了 selectedOptions 中所选项目的数组。实际上,我无法分辨选择了哪个项目。是否有道具或事件可以帮助我跟踪在 Vuetify 1.5.2 中选择的特定项目?
谢谢
解决方法
我已经完成了这个little snippet,你可以试试。
从长远来看,这里是代码:
<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]
在这里为您提供数组中唯一的项目,该项目是前一个选择与当前选择之间差异的结果。
这可能不是最优雅的解决方案,但它适用于选中/取消选中。