【问题标题】:How do I track the item selected in a v-select?如何跟踪在 v-select 中选择的项目?
【发布时间】:2021-04-07 02:33:27
【问题描述】:

我正在使用 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 中选择的特定项目?

谢谢

【问题讨论】:

  • 我不太明白。您说要检索选定的项目。但打勾的是那些被选中的,所以它们在selectedOptions。也许你的意思是你想要那些被选中的新的?
  • 是的,我想你可以说:最后一个被选中(或未选中)。
  • 我提出了一个在选中和取消选中时都有效的答案。

标签: vue.js vuetify.js v-select


【解决方案1】:

我已经完成了这个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 =&gt; !this.previousSelection.includes(x))[0]

对于取消选中,它执行相反的操作,它采用不在选择中但在上一个选择中的:

selected = this.previousSelection.filter(x =&gt; !selection.includes(x))[0]

[0] 在这里为您提供数组中唯一的项,该项是先前选择与当前选择之间的差异的结果。

这可能不是最优雅的解决方案,但它适用于选中/取消选中。

【讨论】:

  • 感谢 Ibris。我在阵列上的手表中做了类似的事情。 v-select 会迫使开发人员实施这样的解决方案似乎很愚蠢,但我想它适用于我们的目的。再次感谢。
  • 这是他们可以根据要求添加的内容。您可以打开功能请求HERE。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-01
  • 1970-01-01
  • 2019-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多