【问题标题】:Vue.js limit selected checkboxes to 5Vue.js 将选中的复选框限制为 5
【发布时间】:2016-02-02 10:28:57
【问题描述】:

我需要将选中复选框的数量限制为 5 个。 我尝试使用 :disabled 像这里:

    <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的时候,所有的复选框都被禁用了,你不能取消选中你不想要的。

我还尝试以 1 毫秒的超时时间拼接数组,这可行,但感觉很 hacky。 谁能推荐一下?

【问题讨论】:

    标签: javascript checkbox vue.js


    【解决方案1】:

    基本上,如果输入尚未被选中并且选择的输入超过 4 个,您只会禁用输入。

    我能想到的最干净的方法是:

    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/

    【讨论】:

    • 像魅力一样工作!谢谢!
    • 请您解释一下“inputs.indexOf(n) === -1”这部分吗?
    • 它检查n是否在数组inputs中。如果是,则不会禁用,因为 inputs.length &gt; 4trueinputs.indexOf(n) === -1 不是。
    猜你喜欢
    • 2017-12-24
    • 2015-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多