uni-app Picker选择器支持多选

发布于 1周前 作者 ionicwang 来自 Uni-App

uni-app Picker选择器支持多选

图片

类似这样的需求实现,但技术有限,效果不理想

1 回复

在uni-app中,Picker 组件默认只支持单选模式,不过你可以通过一些技巧实现多选功能。这通常涉及到自定义一个选择器界面,利用 ListCheckbox 组件来实现多选功能。以下是一个简单的示例,展示如何在uni-app中实现一个支持多选功能的选择器。

1. 创建页面结构

首先,在你的页面中创建一个按钮来触发选择器,以及一个用于显示选中项的列表。

<template>
  <view>
    <button @click="showPicker">选择多项</button>
    <view v-if="selectedItems.length">
      <text>已选择:</text>
      <view v-for="(item, index) in selectedItems" :key="index">
        {{ item }}
      </view>
    </view>
    
    <!-- Picker Modal -->
    <view v-if="isPickerVisible" class="picker-modal" @click.stop="closePicker">
      <view class="picker-overlay" @click="closePicker"></view>
      <scroll-view scroll-y="true" class="picker-content">
        <view v-for="(item, index) in pickerItems" :key="index" class="picker-item" @click="toggleSelect(index)">
          <checkbox :checked="selectedIndices.includes(index)" disabled="false"></checkbox>
          {{ item }}
        </view>
      </scroll-view>
    </view>
  </view>
</template>

2. 定义数据和逻辑

在页面的 <script> 部分,定义数据和逻辑来处理多选功能。

<script>
export default {
  data() {
    return {
      isPickerVisible: false,
      pickerItems: ['选项1', '选项2', '选项3', '选项4'],
      selectedItems: [],
      selectedIndices: []
    };
  },
  methods: {
    showPicker() {
      this.isPickerVisible = true;
      this.selectedItems = [];
      this.selectedIndices = [];
    },
    toggleSelect(index) {
      const isSelected = this.selectedIndices.includes(index);
      if (isSelected) {
        this.selectedIndices = this.selectedIndices.filter(i => i !== index);
      } else {
        this.selectedIndices.push(index);
      }
      this.selectedItems = this.selectedIndices.map(i => this.pickerItems[i]);
    },
    closePicker() {
      this.isPickerVisible = false;
    }
  }
};
</script>

3. 添加样式

为选择器添加一些基本样式,以便更好地显示。

<style>
.picker-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background: rgba(0, 0, 0, 0.5);
}
.picker-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}
.picker-content {
  width: 90%;
  height: 80%;
  background: #fff;
  border-radius: 10px;
  overflow-y: auto;
  padding: 10px;
}
.picker-item {
  display: flex;
  align-items: center;
  padding: 10px;
  border-bottom: 1px solid #eee;
}
</style>

通过上述代码,你可以在uni-app中实现一个支持多选功能的自定义选择器。

回到顶部