多选操作(vue3)

功能1描述:通过下拉菜单进行多选,这里的例子功能最多只能选择4个,如果需要选择多个,更改对应的代码就行。如图:

 功能2描述:进行多选之后,以面包屑的形式展示在上方,并且可以关闭某一项,左边的高亮选择也应做对应的改变,也就是说,左边和上方是同步的。如图:

简单模拟左边的数据结构:

var options = ref([
    {
        id: 1,
        text: '一区',
        chose: 0
    },
    {
        id: 2,
        text: '二区',
        chose: 0
    },
    {
        id: 3,
        text: '三区',
        chose: 0
    },
    {
        id: 4,
        text: '四区',
        chose: 0
    },
    {
        id: 5,
        text: '五区',
        chose: 0
    },
    {
        id: 6,
        text: '六区',
        chose: 0
    },
    {
        id: 7,
        text: '七区',
        chose: 0
    }
]);

基本实现思路: 在选择的时候,收集好对应的索引,根据索引进行高亮显示,并且通过索引修改左边下拉内容项的chose(是否选择的值),通过数组过滤过滤出chose为1的值,即面包屑数组(上方展示的内容)。在面包屑删除某一项的时候,通过id对应删除左边下拉选择的对应数据(把对应的chose值改为0)。

怎么记录所选索引? 

这里使用js 中的一种内置集合数据结构Set。它允许存储一组无序、唯一的值,可以用于去重、过滤和排序等操作。一系列的操作如下:具体说明代码中有进行注释。

// 选择元素的索引
var selected = ref([]);

let count = 0; // 记录已选择的数量
// 拿到标识了哪一个的索引,根据索引去更改原数组的chose值
function toggleSelect(index) {
    // 创建一个新的 Set 数据结构,命名为 selectedSet,并将 selected.value 数组作为初始值传递给 Set 构造函数
    const selectedSet = new Set(selected.value);

    if (selectedSet.has(index)) {
        selectedSet.delete(index);
        count--;
        // 限制最多4个
    } else if (count < 4) {
        selectedSet.add(index);
        count++;
    }
    //   将 selectedSet 这个 Set 数据结构转换为一个数组,并将该数组赋值给 selected.value
    selected.value = Array.from(selectedSet);

    // 更新原数组中的chose值
    options.value.forEach((item, idx) => {
        item.chose = selectedSet.has(idx) ? 1 : 0;
    });
    console.log("options.value",options.value);
    haschose(options.value)
}
// 面包屑数组
var breadList = ref([]);
function haschose(options) {
    const chosenItems = options.filter(item => item.chose === 1);
    console.log("面包屑",chosenItems);
    breadList = chosenItems
}
// 根据索引关闭对应项
function close(index) {
    // 拿到删除项的id把options里面的项做对应更改
    const removedItem = breadList.splice(index, 1)[0];
    const removedItemId = removedItem.id;
  
  // 更新 selected 数组和 count 变量
  const newSelected = [];
  let newCount = 0;
//   遍历options项修改对应id的项的chose中
  options.value.forEach((item, idx) => {
    if (item.id === removedItemId) {
      item.chose = 0;
    }
    if (item.chose === 1) {
        // 更新最新的值
      newSelected.push(idx);
      newCount++;
    }
  });

  selected.value = newSelected;
  count = newCount;
  console.log("关闭之后的options", options.value);
}

猜你喜欢

转载自blog.csdn.net/weixin_62639453/article/details/133365360
今日推荐