uview-plus Picker选择器实现省市区三级联动

发布于:2024-12-08 ⋅ 阅读:(365) ⋅ 点赞:(0)

效果图

 接口返回数据格式如下(可根据接口返回变换示例中的 取/赋值字段

 html

<template>
	<view>
        <view>{{area}}</view>
        <up-picker
            :show="districtPkShow"
            ref="uPickerRef"
            :columns="areaList"
            keyName="name"
            itemHeight="34"
            @confirm="confirmDist"
            @change="distChangeHandler"
            @cancel="distCancel"
            >
        </up-picker>
		<up-button @click="districtPkShow = true">打开省市区选择</up-button>
	</view>
</template>

 script

<script setup>
  import AreaApi from '@/sheep/api/system/area';

  // 使用 reactive 创建响应式状态
  const state = reactive({
    districtPkShow: false,
    area: '',
    areaList: [[], [], []],
  });

  const {
    districtPkShow,
    area,
    areaList,
  } = toRefs(state);

  // 使用 ref 创建响应式引用
  // Picker组件 Ref
  const uPickerRef = ref(null);

  onLoad(async () => {
    // 获取地区列表
    const { code, data } = await AreaApi.getAreaTree();
    if (code === 0) {
        console.log(data, '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>');
        areaList.value[0].push(...data); // 省
        areaList.value[1].push(...areaList.value[0][0].children); // 市
        areaList.value[2].push(...areaList.value[1][0].children); // 区
      }    
  });

  // 监听省市区列表选择器变化
  const distChangeHandler = (item) => {
    const { columnIndex, value } = item;
    let city = value[0].children;
    if (columnIndex === 0) {
      // 省变化更新市、区列表
      // setColumnValues(index, setVal) 设置对应列的选择值
      uPickerRef.value.setColumnValues(1, city);
      uPickerRef.value.setColumnValues(2, city[0].children);
    } else if (columnIndex === 1) {
      // 市变化更新区/县列表
      uPickerRef.value.setColumnValues(2, value[1].children);
    }
  };

  // 确定选择服务地区
  const confirmDist = (item) => {
    const { value } = item;
    settledInfo.value.area = `${value[0].name} / ${value[1].name} / ${value[2].name}`;
    districtPkShow.value = false; // 关闭弹框
  };

  // 取消服务地区选择
  const distCancel = () => {
    districtPkShow.value = false;
  };
</script>

选择结果展示


网站公告

今日签到

点亮在社区的每一天
去签到