uniapp select 多选选择器封装

前言:作者想实现的功能类似一个uniapp选择器,但是可以选择多个值,同时又可以单选和全选,在uniapp  的UI框架去找,发现没有类似的,最后在uniapp 的插件市场找到了这个multiple-select   里面的功能比较全实现了单选全选并同时可以选择多个值,还可以禁用某一项数据,自己做了一下更改记录一下,希望大家以后能用到。

组件封装:multiple-select.vue

<template>
  <view class="select-container" v-show="show" @touchmove.stop.prevent>
    <view
      class="mask"
      :class="activeClass ? 'mask-show' : ''"
      @tap="onCancel(true)"
    ></view>
    <view class="select-box" :class="activeClass ? 'select-box-show' : ''">
      <view class="header">
        <text class="cancel" @tap="onCancel">{{ cancelText }}</text>
        <view class="all" @tap="onAllToggle" v-if="allShow">
          <text :class="isAll ? 'all-active' : ''">全选 </text>
        </view>
        <text class="confirm" @tap="onConfirm">{{ confirmText }}</text>
      </view>
      <view class="body-warp">
        <scroll-view class="body" scroll-y="true">
          <slot v-if="!data.length" name="tips">
            <view class="empty-tips">暂无数据~</view>
          </slot>
          <view
            class="select-item"
            :class="[
              item.disabled ? 'disabled' : '',
              selectedArr[index] ? 'selected' : '',
            ]"
            v-for="(item, index) in data"
            :key="item[valueName]"
            @tap="onSelected(index)"
          >
            <view class="label">{{ item.name }}</view>
            <text v-show="selectedArr[index]" class="selected-icon">✔</text>
          </view>
        </scroll-view>
      </view>
    </view>
  </view>
</template>
<!-- 多选组件 -->
<script>
export default {
  model: {
    prop: "value",
    event: ["input"],
  },

  data() {
    return {
      show: false, //是否显示
      activeClass: false, //激活样式状态
      selectedArr: [], //选择对照列表
      selectedArrOld: [], //选择对照列表上一次的数据
    };
  },
  onShow() {
    this.show = this.value;
    console.log(this.serviceList);
  },
  computed: {
    // 返回是否全选
    isAll() {
      let wipeDisabledList = this.returnWipeDisabledList();
      if (!wipeDisabledList.length) return false;
      return !wipeDisabledList.includes(false);
    },
  },
  props: {
    // 双向绑定
    value: {
      type: Boolean,
      default: false,
    },
    // 取消按钮文字
    cancelText: {
      type: String,
      default: "取消",
    },
    // 确认按钮文字
    confirmText: {
      type: String,
      default: "确认",
    },
    // label对应的key名称
    labelName: {
      type: String,
      default: "label",
    },
    // value对应的key名称
    valueName: {
      type: String,
      default: "value",
    },
    // 是否允许点击遮罩层关闭
    maskCloseAble: {
      type: Boolean,
      default: true,
    },
    // 是否显示全选
    allShow: {
      type: Boolean,
      default: true,
    },
    // 模式
    mode: {
      type: String,
      default: "multiple",
    },
    // 默认选中值
    defaultSelected: {
      type: Array,
      default: function () {
        return [];
      },
    },
    // 数据源
    data: {
      type: Array,
      required: true,
      default: () => {
        return [];
      },
    },
  },
  created() {
    console.log(this.data, "111111");
  },
  watch: {
    async value(newVal) {
      this.show = newVal;
      await this.$nextTick();
      this.activeClass = newVal;
      if (newVal) {
        this.selectedArrOld = JSON.parse(JSON.stringify(this.selectedArr));
      }
    },
    async data(newVal) {
      this.data = newVal;
      await this.$nextTick();
      console.log(this.data);
    },
    show(newVal) {
      this.$emit("input", newVal);
      this.$emit("change", newVal);
    },
    data: {
      // 设置初始选择对照列表
      handler(list) {
        this.selectedArr = list.map((el) => false);
        this.setItemActiveState();
      },
      deep: true,
      immediate: true,
    },
    defaultSelected: {
      handler() {
        this.setItemActiveState();
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    // 设置默认选中通用办法
    setItemActiveState() {
      if (this.data.length && this.defaultSelected.length) {
        this.data.forEach((item, i) => {
          for (let n = 0; n < this.defaultSelected.length; n++) {
            if (
              !item.disabled &&
              item[this.valueName] === this.defaultSelected[n]
            ) {
              this.selectedArr.splice(i, 1, true);
              break;
            }
          }
        });
      }
    },
    /**
     * 选择事件
     * @index {Number} 点击下标
     */
    onSelected(index) {
      if (this.data[index].disabled) return;
      let index2Active = this.selectedArr[index];
      this.selectedArr.splice(index, 1, !index2Active);
    },
    // 取消事件
    onCancel(isMask) {
      if (!isMask || this.maskCloseAble) {
        this.show = false;
        this.selectedArr = JSON.parse(JSON.stringify(this.selectedArrOld));
      } else {
        return;
      }
      this.$emit("cancel");
    },
    // 返回去除了disabled状态后的对照列表
    returnWipeDisabledList() {
      let arr = [];
      this.selectedArr.forEach((el, index) => {
        if (!this.data[index].disabled) arr.push(el);
      });
      return arr;
    },
    // 全选/非全选事件
    onAllToggle() {
      let wipeDisabledList = this.returnWipeDisabledList();
      // 如果去除了disabled的对照列表有false的数据,代表未全选
      if (wipeDisabledList.includes(false)) {
        this.selectedArr.forEach((el, index) => {
          if (!this.data[index].disabled)
            this.selectedArr.splice(index, 1, true);
        });
      } else {
        this.selectedArr.forEach((el, index) => {
          if (!this.data[index].disabled)
            el = this.selectedArr.splice(index, 1, false);
        });
      }
    },
    // 确定事件
    onConfirm() {
      console.log(11212);
      this.show = false;
      let selectedData = [];
      this.selectedArr.forEach((el, index) => {
        if (el) {
          console.log(el);
          selectedData.push(this.data[index]);
        }
      });
      if (this.mode === "multiple") {
        console.log(selectedData);
        this.$emit("confirm", selectedData);
      } else {
        let backData = selectedData[0] || {};
        this.$emit("confirm", backData);
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.select-container {
  width: 100vw;
  height: 100vh;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 999;
  $paddingLR: 18rpx;
  .mask {
    width: 100%;
    height: 100%;
    background-color: $uni-bg-color-mask;
    opacity: 0;
    transition: opacity 0.3s;
    &.mask-show {
      opacity: 1;
    }
  }
  // 选择器内容区域
  .select-box {
    width: 100%;
    position: absolute;
    bottom: 0;
    left: 0;
    transform: translate3d(0px, 100%, 0px);
    background-color: $uni-bg-color;
    transition: all 0.3s;
    &.select-box-show {
      transform: translateZ(0);
    }
    .header {
      display: flex;
      box-sizing: border-box;
      width: 100%;
      justify-content: space-between;
      border-bottom: 1px solid $uni-border-color;
      line-height: 76rpx;
      font-size: 30rpx;
      padding: 0 $paddingLR;
      .cancel {
        color: $uni-text-color-grey;
      }
      .all {
        color: $uni-color-success;
        .all-active {
          &::after {
            display: inline-block;
            content: "✔";
            padding-left: 8rpx;
          }
        }
      }
      .confirm {
        color: $uni-color-primary;
      }
    }
    .body-warp {
      width: 100%;
      height: 30vh;
      box-sizing: border-box;
      padding: 20rpx $paddingLR;
    }
    .body {
      width: 100%;
      height: 100%;
      overflow-y: auto;
      .empty-tips {
        margin-top: 25%;
        text-align: center;
        font-size: 26rpx;
        color: $uni-color-error;
      }
      .select-item {
        display: flex;
        font-size: 26rpx;
        line-height: 58rpx;
        color: #303133;
        position: relative;
        transition: all 0.3s;
        &.selected {
          color: $uni-color-primary;
        }
        &.disabled {
          color: $uni-text-color-disable;
        }
        > .label {
          flex: 1;
          text-align: center;
        }
        > .selected-icon {
          position: absolute;
          right: 0;
          top: 50%;
          transform: translateY(-50%);
        }
      }
    }
  }
}
</style>

组件内使用:

<template>
  <view class="wrap">
   <multiple-select
      v-model="accServiceShow"
      :data="serviceList"
      :default-selected="defaultSelected"
      @confirm="accServiceConfirm"
    ></multiple-select>
  </view>
</template>
<script>
import multipleSelect from "../../components/multiple-select/multiple-select.vue";
export default {
  components: {
    multipleSelect,
  },
  data(){
     return{
        defaultSelected: ["3", "5"], //默认选中项
        serviceList: [],//传递给子组件的数据
    }
}

</script>

注意:该插件非原创作者,如有侵权请联系作者删除

  • 4
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 14
    评论
本课程讲了Vue3+Vue2+Uni-app(uniapp)入门基础与实战,其中还重点讲解了ES6、TypeScript这些基础知识,实战由两大价值5000元的真实企业级项目组成,分别是仿京东电商网站和仿美团微信点餐小程序,同时两大项目代码全部赠送,还赠送前后端架构模板,工作中直接使用。VUE和uni-app是目前热门的前端框架,本课程教你如何快速学会VUE和uni-app并应用到实战,教你如何解决内存泄漏,常用UI库的使用,自己封装组件和插件,正式上线白屏问题,性能优化、解决iphoneX“刘海”兼容性问题、微信支付、微信授权登录,获取位置在地图上显示,获取用户所在的城市和街道信息,微信小程序发布审核等。对正在工作当中或打算学习VUE和uni-app高薪就业的你来说,那么这门课程便是你手中的葵花宝典。学习技巧:学习当中不要只看,一定要多敲代码,如果碰到某一个知识点不是很明白,不要钻牛角尖,千万不要因为一个点,放弃整个森林,接着往下学,硬着头皮开发项目。只要能亲自开发一个完整的项目,你会发现不明白的地方自然而然就明白了,项目做出来就真正的学会了。此vue和uni-app课程以面试和实战为基础进行讲解,每个知识点都会让你知道在实际项目开发中如何使用,学习后,可以开发大型项目,增强逻辑思维,至少让你拥有3年以上开发经验的实力!代码和ppt均可下载!免费提供《企业级完整实战项目接口文档》,绝对可用
uniapp中实现单选、多选和全选的方式有很多种,下面是其中一种可行的方法: 1. 单选 首先,在数据源中添加一个选中属性(例如isSelected),表示该项是否被选中。然后,在模板中使用v-model绑定isSelected属性即可实现单选。 ```html <template> <div> <div v-for="(item, index) in dataList" :key="item.id"> <input type="radio" :value="index" v-model="selectedIndex"> {{ item.name }} </div> </div> </template> <script> export default { data() { return { selectedIndex: -1, dataList: [ { id: 1, name: '选项1', isSelected: false }, { id: 2, name: '选项2', isSelected: false }, { id: 3, name: '选项3', isSelected: false } ] } } } </script> ``` 2. 多选 同样,在数据源中添加一个选中属性(例如isSelected),表示该项是否被选中。然后,在模板中使用v-model绑定一个数组,选中的项会被添加到该数组中。 ```html <template> <div> <div v-for="(item, index) in dataList" :key="item.id"> <input type="checkbox" :value="index" v-model="selectedList"> {{ item.name }} </div> </div> </template> <script> export default { data() { return { selectedList: [], dataList: [ { id: 1, name: '选项1', isSelected: false }, { id: 2, name: '选项2', isSelected: false }, { id: 3, name: '选项3', isSelected: false } ] } } } </script> ``` 3. 全选 首先,在数据源中添加一个选中属性(例如isSelected),表示该项是否被选中。然后,添加一个全选按钮,当点击全选按钮时,将所有项的isSelected属性设置为true或false即可实现全选。 ```html <template> <div> <button @click="selectAll">全选</button> <div v-for="(item, index) in dataList" :key="item.id"> <input type="checkbox" :value="index" v-model="selectedList"> {{ item.name }} </div> </div> </template> <script> export default { data() { return { selectedList: [], dataList: [ { id: 1, name: '选项1', isSelected: false }, { id: 2, name: '选项2', isSelected: false }, { id: 3, name: '选项3', isSelected: false } ] } }, methods: { selectAll() { this.dataList.forEach(item => { item.isSelected = true }) this.selectedList = this.dataList.map((item, index) => index) } } } </script> ``` 以上是实现单选、多选和全选的简单示例,具体的实现方式可以根据实际需要进行调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值