js关于数组多选加限制条件问题

`

arr:[
    {type:'user',isPx:false},
    {type:'user',isPx:false},
    {type:'user',isPx:false},
    {type:'pro',isPx:false},
    {type:'pro',isPx:false},
    {type:'pro',isPx:false},
  ]

`
image.png

怎么做到其中type为user的只能勾选一个,其他type为user不能勾选,type为pro的也只能勾选一个,其他不能勾选。 是想把checkbox的状态改成不可选择状态

阅读 4k
6 个回答

点击的时候,其他user置为false

handle(cur) {
    this.data.forEach(item => {
        if (item.type === cur.type) {
            item.isPx = false;
        }
    });
    cur.isPx = true;
}

最笨的方法

关注一下,数据结构已经这样了还能怎么写?

computed: {

  cities() {
    const map = new Map();
    const dataList = [
{type:'user',isPx:false},
{type:'user',isPx:false},
{type:'user',isPx:false},
{type:'pro',isPx:false},
{type:'pro',isPx:false},
{type:'pro',isPx:false}

];

    dataList.forEach((item, index) => {
      if(this.checkedCities.includes(index)) {
        map.set(item.type, index);
      }
    })
    
    dataList.map((item, index) => {
      if(!map.has(item.type) || map.get(item.type) == index) {
        item.isPx = false;
      } else {
        item.isPx = true;
      }
    })
    return dataList
  }
}

希望对你有用 觉得不对的地方可以自行修改
// 数组成员缺 key 值,应该加上,否则不知道选中的是哪个
handlerClickCheckbox() {
    // 假设 checkbox 绑定的值是 this.value (是个数组)
    // 1.根据 key 值获取出已选的 type 数组
    const typeArr = this.arr.filter(item => this.value.includes(item.key)).map(item => item.type);
    // 2.加标志禁用状态的字段
    this.arr = this.arr.map(item => {
        return {
            ...item,
            // 同时满足两个条件就是禁用状态:
            // 1.type 相同 2.key 不在已选值内
            disabled: (typeArr.includes(item.type)) && !this.value.includes(item.key)
        }
    })
}

Element UI 是基于 Vue 数据驱动的

el-checkbox 有一个 change 事件,在这里可以处理 this.arr,循环把所有同类型的,除了自己都设置为 false

不需要 Disable,反正实现出来的效果应该是分类单选

现在唯一的问题是能不能在事件里找到当前点击的这一个,要试下才晓得

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题