封装一个小程序选择器(可多选、单选、搜索)

news2025/7/22 18:19:15

组件

<template>
  <view class="popup" v-show="show">
    <view class="bg" @tap="cancelMultiple"></view>
    <view class="selectMultiple">
      <view class="multipleBody">
        <view class="title">
          <view class="close" @tap="cancelMultiple">
            取消
          </view>
          <view class="name">
            <!-- cancelButton="none" 不展示取消按钮-->
            <uni-search-bar
                @input="updateList"
                @confirm="onSearchConfirm"
                cancelButton="none">
            </uni-search-bar>

          </view>
          <view class="confirm" @tap="confirmMultiple">
            确认
          </view>
        </view>
        <view class="list">
          <view class="mask mask-top"></view>
          <view class="mask mask-bottom"></view>
          <scroll-view class="diet-list" scroll-y="true">
            <view v-for="(item, index) in list" :class="['item', item.selected ? 'checked' : '']" @tap="onChange(index, item)">
              <span style="font-size: 16px;">{{item.label}}</span>
              <view class="icon" v-show="item.selected">
                <icon type="success_no_circle" size="16" color="#2D8DFF"/>
              </view>
            </view>
          </scroll-view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  name:"my-curry-multi-select",
  data() {
    return {
      // 选中值
      value: [],
      // 选中列表
      selected: [],
      // 列表数据
      list: [],
      originList: [],
    };
  },
  props: {
    // 是否显示
    show: {
      type: Boolean,
      default: false
    },
    // 标题
    title: {
      type: String,
      default: ''
    },
    //数据列表
    columns: {
      type: Array,
      default: []
    },
    // 默认选中
    defaultIndex: {
      type: Array,
      default: [],
    },
    isMultiSelect: {
      type: Boolean,
      default: true
    },
  },
  watch: {
    // 监听是否显示
    show(val) {
      if(val) {
        this.openMultiple();
      }
    }
  },
  methods: {
    sortListWithSelectedFirst(list) {
      return list.slice().sort((a, b) => {
        const aSelected = a.selected ? 1 : 0;
        const bSelected = b.selected ? 1 : 0;
        return bSelected - aSelected;
      });
    },
    updateList(str) {
      this.list.map(e => {
        this.originList.map(item => {
          if (e.selected && item.value === e.value) {
            item.selected = true
          }
        })
      })

      if (str === null || str === undefined || str === '') {
        this.list = JSON.parse(JSON.stringify(this.originList))
      } else {
        const filtered = this.originList.filter(e => e.label.indexOf(str) > -1 || e.selected);
        this.list = this.sortListWithSelectedFirst(filtered);
      }
    },
    // 新增:处理搜索确认事件
    onSearchConfirm(e) {
      const searchValue = e.value || e;

      // 先更新列表
      this.updateList(searchValue);

      // 如果有搜索内容且搜索结果不为空,自动选择第一个未选中的项目
      if (searchValue && this.list.length > 0) {
        // 找到第一个未选中的项目
        const firstUnselectedIndex = this.list.findIndex(item => !item.selected);

        if (firstUnselectedIndex !== -1) {
          // 自动选择第一个未选中的项目
          this.onChange(firstUnselectedIndex, this.list[firstUnselectedIndex]);
        }
      }
    },
    // 列点击事件
    onChange(index, item) {
      // 单选
      if (!this.isMultiSelect) {
        this.value = [];
        this.selected = [];
        this.value.push(item.value.toString());
        this.selected.push({
          label: item.label,
          value: item.value,
        });
        return this.$emit("confirm", {selected: this.selected, value: this.value});
      }
      // 是否已选中
      if(this.value.indexOf(item.value.toString()) >= 0) {
        this.list[index].selected = false;
      } else {
        this.list[index].selected = true;
      }

      // 筛选已勾选数据
      this.value = [];
      this.selected = [];
      this.list.forEach((col_item, col_index) => {
        if(col_item.selected) {
          this.value.push(col_item.value.toString());
          this.selected.push({
            label: col_item.label,
            value: col_item.value,
          });
        }
      });
      this.list = this.sortListWithSelectedFirst(this.list);
      this.$emit("change", {selected: this.selected, value: this.value});
    },
    // 弹出框开启触发事件
    openMultiple() {
      // 初始化列表数据,默认勾选数据
      this.value = this.defaultIndex;
      this.columns.forEach((item, index) => {
        this.$set(item, "selected", false);
        if(this.value.indexOf(item.value.toString()) >= 0) {
          item.selected = true;
        }
      });
      this.originList = Object.assign([], this.columns);
      this.list = this.sortListWithSelectedFirst(JSON.parse(JSON.stringify(this.originList)));
    },
    // 确认
    confirmMultiple() {
      this.$emit("confirm", {selected: this.selected, value: this.value});
    },
    // 关闭/取消
    cancelMultiple() {
      this.$emit("cancel");
    },
  }
}
</script>

<style scoped lang="scss">
.popup {
  width: 100%;
  height: 100vh;
  position: fixed;
  z-index: 99999;
  left: 0;
  top: 0;

  .bg {
    width: 100%;
    height: 100%;
    background-color: rgba(black, .5);
  }
}
.selectMultiple {
  transition: none !important;
  will-change: transform;
  width: 100%;
  position: absolute;
  left: 0;
  top: 0;
  height: 50vh;
  background-color: white;
  border-radius: 0 0 20rpx 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
  overflow: hidden;

  .multipleBody {
    width: 100%;
    height: 100%;
    padding: 30rpx;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    .title {
      flex-shrink: 0;
      font-size: 28rpx;
      display: flex;
      flex-direction: row;
      align-items: center; /* 添加这一行 */

      .close {
        width: 80rpx;
        text-align: left;
        opacity: .5;
      }
      .name {
        width: 530rpx;
        text-align: center;
        overflow: hidden;
        display: -webkit-box;
        -webkit-box-orient:vertical;
        -webkit-line-clamp:1;
      }
      .confirm {
        width: 80rpx;
        text-align: right;
        color: #2D8DFF;
      }
    }
    .list {
      flex: 1;
      overflow: hidden;
      width: 100%;
      padding-top: 30rpx;
      position: relative;

      .mask {
        width: 100%;
        height: 60rpx; // 减小渐变区域
        position: absolute;
        left: 0;
        z-index: 2;
        pointer-events: none;

        &.mask-top {
          top: 30rpx;
          background-image: linear-gradient(to bottom, #fff, rgba(#fff, 0));
        }
        &.mask-bottom {
          bottom: 0;
          background-image: linear-gradient(to bottom, rgba(#fff, 0), #fff);
        }
      }

      .diet-list {
        height: 100%;
        max-height: none;
      }

      .item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 20rpx 0;
        border-bottom: 1px solid rgba(#000, 0.05);

        span {
          flex: 1;
          font-size: 30rpx;
          text-align: center;
        }

        .icon {
          width: 32rpx;
          height: 32rpx;
        }
        &.checked {
          color: #2D8DFF;
        }
        &:last-child {
          border-bottom: none;
          margin-bottom: 60rpx;
        }
        &:first-child {
          margin-top: 60rpx;
        }
      }
    }
  }
}
</style>

使用

<template>
  <view class="container">
    <view>
      <uni-forms ref="taskForm" :model="taskForm" labelWidth="80px">
        <!-- 任务类型单选 -->
        <uni-forms-item label="任务类型" name="type">
          <view class="item">
            <view :class="['select', taskForm.type ? 'selected' : '']"
                  @tap="openTypeSelectionBox(taskForm.type)">
              {{ taskForm.type ? getTaskTypeName(taskForm.type) : '请选择任务类型' }}
            </view>
            <!-- 如果有内容显示关闭图标 -->
            <uni-icons v-if="taskForm.type !== ''" type="clear" size="24" color="#c0c4cc" class="close-btn"
                       @tap="clearType"></uni-icons>
            <!-- 如果没有内容显示下拉图标 -->
            <uni-icons v-else type="pulldown" size="24" color="#c0c4cc" class="close-btn"
                       @tap="openTypeSelectionBox(taskForm.type)"></uni-icons>

            <my-curry-multi-select title="请选择" :show="taskTypeShow" :columns="taskTypeList"
                                   :defaultIndex="defaultTaskTypeIndex"
                                   :isMultiSelect="false"
                                   @confirm="confirmType($event)"
                                   @cancel="taskTypeShow = false"></my-curry-multi-select>
          </view>
        </uni-forms-item>
        <!-- 负责人多选 -->
        <uni-forms-item label="负责人" name="personInChargeIds">
          <view class="item">
            <view :class="['select', (Array.isArray(taskForm.personInChargeIds) && taskForm.personInChargeIds.length > 0) ? 'selected' : '']"
                  @tap="openPersonInChargeIdsMultiSelectionBox(taskForm.personInChargeIds)">
              {{ (Array.isArray(taskForm.personInChargeIds) && taskForm.personInChargeIds.length > 0)
                ? getUserNamesByIds(taskForm.personInChargeIds)
                : '请选择负责人' }}
            </view>
            <uni-icons v-if="Array.isArray(taskForm.personInChargeIds) && taskForm.personInChargeIds.length > 0"
                       type="clear" size="24" color="#c0c4cc" class="close-btn"
                       @tap="clearPersonInChargeIds"></uni-icons>
            <uni-icons v-else type="pulldown" size="24" color="#c0c4cc" class="close-btn"
                       @tap="openPersonInChargeIdsMultiSelectionBox(taskForm.personInChargeIds)"></uni-icons>

            <my-curry-multi-select title="请选择" :show="taskTaskPersonInChargesShow"
                                   :columns="userList"
                                   :defaultIndex="defaultTaskPersonInChargesIndex"
                                   :isMultiSelect="true"
                                   @confirm="confirmPersonInChargeIds($event)"
                                   @cancel="taskTaskPersonInChargesShow = false"></my-curry-multi-select>
          </view>
        </uni-forms-item>

      </uni-forms>
      <button type="primary" @click="submit">提交</button>
    </view>
  </view>
</template>

<script>
import myCurryMultiSelect from "@/components/curry-multi-select/my-curry-multi-select.vue";

export default {
  components: {myCurryMultiSelect},
  data() {
    return {
      // 当前正选择哪个任务类型元素
      defaultTaskTypeIndex: [],
      // 任务类型列表,单选
      taskTypeList: [
        {"label": "指派任务", "value": 1},
        {"label": "设计任务", "value": 2},
        {"label": "代办", "value": 2}
      ],
      // 是否展示任务类型下拉选项
      taskTypeShow: false,

      // 当前正选择哪些任务负责人元素
      defaultTaskPersonInChargesIndex: [],
      // 是否展示任务负责人下拉选项
      taskTaskPersonInChargesShow: false,
      // 用户列表,多选
      userList: [
        { value: 1, label: '张三' },
        { value: 2, label: '李四' },
        { value: 3, label: '王五' },
      ],

      // 表单数据
      taskForm: {
        taskTitle: '',
        insertUser: '',
        type: 2,
        personInChargeIds: [1,2],
        personInChargeId: null,
        taskContent: '',
        requiredCompletionTime: '',
        actualCompletionTime: '',
        weight: '',
        weightScore: '',
        timeoutStatus: '0',
        participants: [],
        taskPictureUrl: [],
        taskFileUrl: [],
        useSchedule: '1',
        standardWorkingHours: '',
      },
      // 表单验证规则
      rules: {
        type: {
          rules: [{required: true, errorMessage: '任务类型不能为空'}]
        },
        personInChargeIds: {
          rules: [
            {
              required: true,
              errorMessage: '负责人不能为空',
              validateFunction: (rule, value) => {
                return Array.isArray(value) && value.length > 0;
              }
            }
          ]
        },
      },
    }
  },
  onLoad() {

  },
  created() {

  },
  onReady() {
    this.$refs.taskForm.setRules(this.rules)
  },
  methods: {
    // =====单选====
    // 打开任务类型选择框
    openTypeSelectionBox(val) {
      console.log('执行了openTypeSelectionBox,展开选择框时val值是:', val)
      this.defaultTaskTypeIndex = val !== '' ? [String(val)] : [];
      console.log('this.defaultTaskTypeIndex',this.defaultTaskTypeIndex)
      this.taskTypeShow = true;
    },
    // 清空类型选择框
    clearType() {
      this.defaultTaskTypeIndex = [];
      this.taskForm.type = '';
    },
    // 获取任务类型名称,把值转换为名称显示出来
    getTaskTypeName(value) {
      const option = this.taskTypeList.find(item => String(item.value) === String(value));
      return option ? option.label : '请选择任务类型';
    },
    // 确认选择任务类型
    confirmType(e) {
      // e是一个数组
      this.taskForm.type = e.value[0];
      this.taskTypeShow = false;
    },


    // =====多选====
    // 打开负责人多选框
    openPersonInChargeIdsMultiSelectionBox(val) {
      console.log('执行了openPersonInChargeIdsMultiSelectionBox,展开选择框时val值是:', val)
      this.defaultTaskPersonInChargesIndex = Array.isArray(val) ? val.map(item => String(item)) : [];
      console.log('this.defaultTaskPersonInChargesIndex', this.defaultTaskPersonInChargesIndex)
      this.taskTaskPersonInChargesShow = true;
    },
    // 清空负责人选择框
    clearPersonInChargeIds() {
      this.defaultTaskPersonInChargesIndex = [];
      this.taskForm.personInChargeIds = null; // 继续保持你的设定
    },

    // 获取任务负责人名称,把值转换为名称显示出来
    getUserNamesByIds(values) {
      if (!Array.isArray(values) || values.length === 0) return '请选择负责人';
      const labels = values.map(value => {
        const option = this.userList.find(item => String(item.value) === String(value));
        return option ? option.label : value;
      });
      return labels.join(',');
    },
    // 确认选择任务负责人
    confirmPersonInChargeIds(e) {
      // e是一个数组
      this.taskForm.personInChargeIds = e.value;
      this.taskTaskPersonInChargesShow = false;
    },

    // 提交表单
    submit() {
      console.log('提交时表单数据是:', this.taskForm)
      // 就是上面这个写法有一个问题,就是提交的时候,选择框的绑定的都是字符串。就是是数值,也是转为字符串的。但是前段字符串,后端用Long也能接收。所以问题不大。
      this.$refs.taskForm.validate().then(res => {
        this.$modal.msgSuccess("修改成功")
      })
    },
  }
}
</script>

<style lang="scss">
.item {
  width: 100%;
  padding: 0;
  position: relative;
  display: flex;
  align-items: center;
  height: 35px;

  .select {
    flex-grow: 1;
    border: 1px solid #dadbde;
    padding: 4px 9px;
    border-radius: 4px;
    font-size: 12px;
    box-sizing: border-box;
    color: #6a6a6a;
    line-height: 25px;
    height: 100%;
    overflow: hidden;

    &.selected {
      color: black;
      font-size: 15px;
    }
  }

  .close-btn {
    position: absolute;
    right: 6px;
    top: 50%;
    transform: translateY(-50%);
    color: red;
    cursor: pointer;
  }
}
</style>

效果

效果:

企业微信截图_17483173394654.png

企业微信截图_17483173487807.png

个人站点链接

我的博客链接:https://blog.yimengtut.online/

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2394807.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Dest建筑能耗模拟仿真功能简介

Dest建筑能耗模拟仿真功能简介 全球建筑能耗占终端能源消费的30%以上&#xff0c;掌握建筑能耗模拟是参与绿色建筑认证&#xff08;如LEED、WELL&#xff09;、超低能耗设计、既有建筑节能改造的必备能力。DEST作为国内主流建筑能耗模拟工具&#xff0c;广泛应用于设计院、咨询…

【Hot 100】121. 买卖股票的最佳时机

目录 引言买卖股票的最佳时机我的解题 &#x1f64b;‍♂️ 作者&#xff1a;海码007&#x1f4dc; 专栏&#xff1a;算法专栏&#x1f4a5; 标题&#xff1a;【Hot 100】121. 买卖股票的最佳时机❣️ 寄语&#xff1a;书到用时方恨少&#xff0c;事非经过不知难&#xff01; 引…

【机器学习基础】机器学习入门核心算法:XGBoost 和 LightGBM

机器学习入门核心算法&#xff1a;XGBoost 和 LightGBM 一、算法逻辑XGBoost (eXtreme Gradient Boosting)LightGBM (Light Gradient Boosting Machine) 二、算法原理与数学推导目标函数&#xff08;二者通用&#xff09;二阶泰勒展开&#xff1a;XGBoost 分裂点增益计算&#…

Linux | Shell脚本的常用命令

一. 常用字符处理命令 1.1 连续打印字符seq seq打印数字&#xff1b;且只能正向打印&#xff0c;不可反向连续打印 设置打印步长 指定打印格式 1.2 反向打印字符tac cat 正向&#xff0c;tac 反向 1.3 打印字符printf printf "打印的内容"指定格式打印内容 换行…

【JUC】深入解析 JUC 并发编程:单例模式、懒汉模式、饿汉模式、及懒汉模式线程安全问题解析和使用 volatile 解决内存可见性问题与指令重排序问题

单例模式 单例模式确保某个类在程序中只有一个实例&#xff0c;避免多次创建实例&#xff08;禁止多次使用new&#xff09;。 要实现这一点&#xff0c;关键在于将类的所有构造方法声明为private。 这样&#xff0c;在类外部无法直接访问构造方法&#xff0c;new操作会在编译…

2025年全国青少年信息素养大赛复赛C++算法创意实践挑战赛真题模拟强化训练(试卷3:共计6题带解析)

2025年全国青少年信息素养大赛复赛C++算法创意实践挑战赛真题模拟强化训练(试卷3:共计6题带解析) 第1题:四位数密码 【题目描述】 情报员使用4位数字来传递信息,同时为了防止信息泄露,需要将数字进行加密。数据加密的规则是: 每个数字都进行如下处理:该数字加上5之后除…

Mongodb | 基于Springboot开发综合社交网络应用的项目案例(中英)

目录 Project background Development time Project questions Create Project create springboot project project framework create folder Create Models user post Comment Like Message Serive tier user login and register Dynamic Publishing and Bro…

飞腾D2000与FPGA结合的主板

UD VPX-404是基于高速模拟/数字采集回放、FPGA信号实时处理、CPU主控、高速SSD实时存储架构开发的一款高度集成的信号处理组合模块&#xff0c;采用6U VPX架构&#xff0c;模块装上外壳即为独立整机&#xff0c;方便用户二次开发。 UD VPX-404模块的国产率可达到100%&#xff0…

百度量子蜘蛛3.0横空出世,搜索引擎迎来“量子跃迁“级革命

一、量子蜘蛛3.0的三大颠覆性升级 1. 动态抓取&#xff1a;让内容实时"量子纠缠" - 智能频率调节&#xff1a;根据网站更新频率自动调整抓取节奏&#xff0c;新闻类站点日抓取量达3-5次&#xff0c;静态页面抓取间隔延长至72小时。某财经媒体通过"热点事件15分钟…

GitHub开源|AI顶会论文中文翻译PDF合集(gpt-translated-pdf-zh)

项目核心特点 该项目专注于提供计算机科学与人工智能领域的高质量中文翻译资源&#xff0c;以下为关键特性&#xff1a; 主题覆盖广泛&#xff1a;包含算法、数据结构、概率统计等基础内容&#xff0c;以及深度学习、强化学习等前沿研究方向。格式统一便捷&#xff1a;所有文…

Drawio编辑器二次开发

‌ Drawio &#xff08;现更名为 Diagrams.net &#xff09;‌是一款完全免费的在线图表绘制工具&#xff0c;由 JGraph公司 开发。它支持创建多种类型的图表&#xff0c;包括流程图、组织结构图、UML图、网络拓扑图、思维导图等&#xff0c;适用于商务演示、软件设计等多种场景…

1.测试过程之需求分析和测试计划

测试基础 流程 1.分析测试需求 2.编写测试计划 3.设计与编写测试用例 4.执行测试 5.评估与总结 测试目标 根据测试阶段不同可分为四个主要目标&#xff1a;预防错误&#xff08;早期&#xff09;、发现错误&#xff08;开发阶段&#xff09;、建立信心&#xff08;验收阶段&a…

[春秋云镜] CVE-2023-23752 writeup

首先奉上大佬的wp表示尊敬&#xff1a;&#xff08;很详细&#xff09;[ 漏洞复现篇 ] Joomla未授权访问Rest API漏洞(CVE-2023-23752)_joomla未授权访问漏洞(cve-2023-23752)-CSDN博客 知识点 Joomla版本为4.0.0 到 4.2.7 存在未授权访问漏洞 Joomla是一套全球知名的内容管理…

CSS专题之水平垂直居中

前言 石匠敲击石头的第 16 次 在日常开发中&#xff0c;经常会遇到水平垂直居中的布局&#xff0c;虽然现在基本上都用 Flex 可以轻松实现&#xff0c;但是在某些无法使用 Flex 的情况下&#xff0c;又应该如何让元素水平垂直居中呢&#xff1f;这也是一道面试的必考题&#xf…

(新)MQ高级-MQ的可靠性

消息到达MQ以后&#xff0c;如果MQ不能及时保存&#xff0c;也会导致消息丢失&#xff0c;所以MQ的可靠性也非常重要。 一、数据持久化 为了提升性能&#xff0c;默认情况下MQ的数据都是在内存存储的临时数据&#xff0c;重启后就会消失。为了保证数据的可靠性&#xff0c;必须…

Leetcode 3231. 要删除的递增子序列的最小数量

1.题目基本信息 1.1.题目描述 给定一个整数数组 nums&#xff0c;你可以执行任意次下面的操作&#xff1a; 从数组删除一个 严格递增 的 子序列。 您的任务是找到使数组为 空 所需的 最小 操作数。 1.2.题目地址 https://leetcode.cn/problems/minimum-number-of-increas…

4.2.5 Spark SQL 分区自动推断

在本节实战中&#xff0c;我们学习了Spark SQL的分区自动推断功能&#xff0c;这是一种提升查询性能的有效手段。通过创建具有不同分区的目录结构&#xff0c;并在这些目录中放置JSON文件&#xff0c;我们模拟了一个分区表的环境。使用Spark SQL读取这些数据时&#xff0c;Spar…

【图像处理入门】2. Python中OpenCV与Matplotlib的图像操作指南

一、环境准备 import cv2 import numpy as np import matplotlib.pyplot as plt# 配置中文字体显示&#xff08;可选&#xff09; plt.rcParams[font.sans-serif] [SimHei] plt.rcParams[axes.unicode_minus] False二、图像的基本操作 1. 图像读取、显示与保存 使用OpenCV…

Spring Boot微服务架构(九):设计哲学是什么?

一、Spring Boot设计哲学是什么&#xff1f; Spring Boot 的设计哲学可以概括为 ​​“约定优于配置”​​ 和 ​​“开箱即用”​​&#xff0c;其核心目标是​​极大地简化基于 Spring 框架的生产级应用的初始搭建和开发过程​​&#xff0c;让开发者能够快速启动并运行项目…

TC/BC/OC P2P/E2E有啥区别?-PTP协议基础概念介绍

前言 时间同步网络中的每个节点&#xff0c;都被称为时钟&#xff0c;PTP协议定义了三种基本时钟节点。本文将介绍这三种类型的时钟&#xff0c;以及gPTP在同步机制上与其他机制的区别 本系列文章将由浅入深的带你了解gPTP&#xff0c;欢迎关注 时钟类型 在PTP中我们将各节…