uni-popup封装多级联动组件
时间: 2025-05-26 17:18:52 浏览: 19
### 使用 `uni-popup` 实现多级联动组件
#### 组件介绍
`uni-popup` 是 UniApp 提供的一个弹窗组件,支持多种类型的弹出层展示。为了实现多级联动功能,通常会结合其他数据处理逻辑一起使用。
#### 创建多级联动组件
##### HTML 结构
首先,在页面中引入 `uni-popup` 并定义触发按钮:
```html
<template>
<view class="content">
<!-- 触发器 -->
<button type="primary" @click="openPopup">选择地区</button>
<!-- 多级联动popup -->
<uni-popup ref="popup" type="center">
<picker-view indicator-style="height: 50px;" :value="currentValue" @change="bindChange">
<picker-view-column>
<div v-for="(item, index) in provinceList" :key="index">{{ item }}</div>
</picker-view-column>
<picker-view-column>
<div v-for="(item, index) in cityList" :key="index">{{ item }}</div>
</picker-view-column>
<picker-view-column>
<div v-for="(item, index) in areaList" :key="index">{{ item }}</div>
</picker-view-column>
</picker-view>
<button @click="confirmSelection">确认</button>
</uni-popup>
</view>
</template>
```
##### JavaScript 部分
接着编写相应的 Vue.js 脚本部分来管理状态和交互行为:
```javascript
<script>
export default {
data() {
return {
currentValue: [0, 0, 0], // 默认选中的索引数组
provinceList: ['广东省', '湖南省'], // 省份列表
cityList: [], // 城市列表 (动态加载)
areaList: [] // 地区列表 (动态加载)
}
},
methods: {
openPopup() {
this.$refs.popup.open()
},
bindChange(e) {
const val = e.detail.value;
this.currentValue = val;
// 动态更新城市和地区列表...
this.updateCityAndArea(val);
},
updateCityAndArea(indexes) {
let selectedProvinceIndex = indexes[0];
switch(selectedProvinceIndex){
case 0:
this.cityList=['广州市','深圳市'];
break;
case 1:
this.cityList=['长沙市','株洲市'];
break;
}
if(this.cityList.length>indexes[1]){
this.areaList=[this.cityList[indexes[1]]+'辖区A',this.cityList[indexes[1]]+'辖区B']
}else{
this.areaList=[];
}
},
confirmSelection(){
console.log('最终选择:', ...this.provinceList[this.currentValue[0]],
this.cityList[this.currentValue[1]],
this.areaList[this.currentValue[2]]);
this.$refs.popup.close();
}
}
}
</script>
```
此代码片段展示了如何利用 `uni-popup` 和 `picker-view` 来构建一个多级联的选择器,并实现了基本的数据绑定与事件监听机制[^1]。
#### 样式调整
可以根据实际需求自定义样式,比如修改字体大小、背景色等,使组件更贴合应用的整体风格。
阅读全文
相关推荐


















