最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to limit selected items in vue-select? - Stack Overflow

programmeradmin5浏览0评论

I use vue-select for multiple values. Here is an example:

I have the following code:

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

And JS:

Vueponent('v-select', VueSelect.VueSelect)

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

Thank you!

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.ponent('v-select', VueSelect.VueSelect)

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

Thank you!

Share Improve this question edited Mar 7, 2018 at 15:44 Bhojendra Rauniyar 85.6k36 gold badges176 silver badges239 bronze badges asked Mar 7, 2018 at 15:07 JarvisJarvis 4152 gold badges7 silver badges18 bronze badges 3
  • What to limit?? – Bhojendra Rauniyar Commented Mar 7, 2018 at 15:09
  • @BhojendraNepal, selected tags – Jarvis Commented Mar 7, 2018 at 15:17
  • 1 Check my answer and let me know if this is what you wanted. – Bhojendra Rauniyar Commented Mar 7, 2018 at 15:45
Add a ment  | 

4 Answers 4

Reset to default 12

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

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.

you can use

:selectable="() => selected.length < 3"

from the official documentation https://vue-select/guide/selectable.html#limiting-the-number-of-selections

@update:modelValue="(e) => { (e.length > 2) && e.shift(); a = e }"

'a' is your model value

 <v-select
      v-model="selectedLlm"
      density="pact"
      label="Model"
      style="font-size: 12px"
      :items="languageModels"
      multiple
      hide-details
      chips
      @update:modelValue="(e) => { (e.length > 3) && e.shift(); selectedLlm = e }"
    ></v-select>
发布评论

评论列表(0)

  1. 暂无评论