Vue.js将选定的复选框限制为5 [英] Vue.js limit selected checkboxes to 5

查看:544
本文介绍了Vue.js将选定的复选框限制为5的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将所选复选框的数量限制为5。
我尝试使用:disabled如下:

I need to limit number of selected checkboxes to 5. I tried using :disabled like here:

    <ul>
        <li v-for="item in providers">
            <input type="checkbox" 
               value="{{item.id}}" 
               id="{{item.id}}" 
               v-model="selected_providers" 
               :disabled="limit_reached" 
            >
        </li>
    </ul>

然后:

new Vue({
    el: '#app',
    computed:{
        limit_reached: function(){
            if(this.selected_providers.length > 5){
                return true;
            }
            return false;
        }
    }
})

这种方法有效,但是当其达到5时,所有复选框均被禁用,您无法取消选中不需要的复选框。

This kind of works, but when it reaches 5, all of the check boxes are disabled and you can't uncheck the ones you don't want.

我还试图以1毫秒的超时时间对数组进行拼接,该方法可以正常工作,但感觉很笨拙。
有人可以推荐任何东西吗?

I also tried to splice the array with timeout of 1 ms, which works but feels hacky. Can anyone recommend anything please?

推荐答案

基本上,只有在未选择输入的情况下,您才禁用该输入,

Basically, you'd only disable the input if it's not already selected and there's more than 4 of them selected.

我想出的最干净的方法是:

The cleanest way I could come up with was:

new Vue({
  el: '#app',
  data: {
    inputs: []
  }
})

使用:

<ul>
  <li v-for="n in 10">
    <label>
      <input
        type="checkbox"
        v-model="inputs"
        :value="n"
        :disabled="inputs.length > 4 && inputs.indexOf(n) === -1" 
        number> Item {{ n }} {{ inputs.indexOf(n) }}
    </label>
  </li>
</ul>

这是一个快速演示: https://jsfiddle.net/crswll/axemcp8d/1/

这篇关于Vue.js将选定的复选框限制为5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆