uniapp picker组件实现二级联动

在这里插入图片描述
效果图如上

html

<picker mode="multiSelector" @change="bindPickerChange" @columnchange="columnchange" :value="index" :range="array"
	 range-key="title">
	<view class="uni-input">{{title}}</view>

</picker>

js

<script>
	export default {
		data() {
			return{
				index: [0, 0],
				array: [[],[]],
				childArr: [], // 二级分类数据源
				title: '请选择',
			}
		},
		methods: {
			// 任务分类
			getCate() {
				this.Get('请求的接口地址').then((res) => {
					if (!res.err) {
						// 返回的数据格式
						// [
							// {id: 4, title: "悬赏", desc: "", child: [{id: 10, title: "现金悬赏", desc: ""}]}
						// ]
						// 一级分类的数据源
						this.array[0] = res.result
						// 将数据源中的二级分类 push 进 childArr,作为二级分类的数据源
						this.childArr = res.result.map((item) => item.child)
						// 第一次打开时,默认给一级分类添加它的二级分类
						this.array[1] = this.childArr[0]
					}
				})
			},
			// 获取二级分类
			columnchange(e) {
				// 当滚动切换一级分类时,为当前的一级分类添加它的子类
				if (e.detail.column == 0) {
					// #ifdef H5
					// 在小程序中直接赋值无效  H5 可直接赋值
					this.array[1] = this.childArr[e.detail.value]
					// #endif
					// #ifdef MP-WEIXIN
					// 在 H5 环境下 $set 会导致一级分类无法滚动, 小程序正常运行
					this.$set(this.array, 1, this.childArr[e.detail.value])
					// #endif
				}
			},

			// 选择任务分类
			bindPickerChange: function(e) {
				console.log('picker发送选择改变,携带值为', e.target.value)
				let value = e.target.value;
				this.index = value;
				if (this.array[0].length != 0) {
					this.title = this.array[0][this.index[0]].title
				};
				if (this.array[1].length != 0) {
					this.title += ',' + this.array[1][this.index[1]].title
				}

			},
		}
	}
</script>
  • 3
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值