How to limit selected items in vue-select?

旧巷老猫 提交于 2020-07-22 06:06:09

问题


I use vue-select for multiple values. Here is an example: https://codepen.io/sagalbot/pen/opMGro

I have the following code:

<v-select multiple v-model="selected" :options="options"></v-select>

And JS:

Vue.component('v-select', VueSelect.VueSelect)

new Vue({
  el: '#app',
  data: {
    selected: ['foo','bar'],
    options: ['foo','bar','baz']
  }

Thank you!


回答1:


You can use the v-on:input listener to see how many items are selected.

Then pass it a simple function as:

 <v-select multiple v-model="selected" :options="options" v-on:input="limiter"></v-select>

After this, create a function called limiter in your methods and you'll get the current list of selected inputs,as

  methods: {
    limiter(e) {
      if(e.length > 2) {
        console.log(' you can only select two', e)
        e.pop()
      }
    },
  }

Now, if you add more than 2 items then the last one will be remove and you will see the console log




回答2:


You can simply use inline condition:

<v-select multiple v-model="selected" :options="selected.length < 2 ? options: []">

I have limited to 2 options in the example above. The options will not be generated if there are 2 options selected. Remove the selected one and then you'll see the options dropdown.

Here's the updated demo.



来源:https://stackoverflow.com/questions/49155120/how-to-limit-selected-items-in-vue-select

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!