uniapp如何用scroll-view实现下拉列表二级标题可滑动选择
时间: 2023-11-27 13:03:27 浏览: 153
要实现下拉列表二级标题可滑动选择,可以使用uni-app提供的`scroll-view`组件。
首先,在需要使用的页面中引入`scroll-view`组件:
```vue
<template>
<view>
<scroll-view class="picker-scroll-view" scroll-y>
<view class="picker-content">
<view v-for="item in pickerData" class="picker-item" @click="toggleChildren(item)">
<text class="picker-item-label">{{ item.label }}</text>
<view class="picker-item-children" :class="{ 'show-children': item.showChildren }">
<view v-for="child in item.children" class="picker-item-child" @click="selectChild(item, child)">
<text class="picker-item-child-label">{{ child.label }}</text>
</view>
</view>
</view>
</view>
</scroll-view>
</view>
</template>
<script>
export default {
data() {
return {
pickerData: [
{
label: '标题1',
value: 'title1',
children: [
{ label: '选项1', value: 'option1' },
{ label: '选项2', value: 'option2' },
{ label: '选项3', value: 'option3' }
],
showChildren: false
},
{
label: '标题2',
value: 'title2',
children: [
{ label: '选项4', value: 'option4' },
{ label: '选项5', value: 'option5' },
{ label: '选项6', value: 'option6' }
],
showChildren: false
}
]
}
},
methods: {
toggleChildren(item) {
item.showChildren = !item.showChildren;
},
selectChild(parent, child) {
console.log(parent.value, child.value);
parent.showChildren = false;
}
}
}
</script>
<style>
.picker-scroll-view {
height: 400rpx;
background-color: #f5f5f5;
}
.picker-content {
padding: 20rpx;
}
.picker-item {
display: flex;
justify-content: space-between;
align-items: center;
height: 100rpx;
}
.picker-item-label {
font-size: 32rpx;
}
.picker-item-children {
display: none;
flex-direction: column;
}
.picker-item-children.show-children {
display: flex;
}
.picker-item-child {
height: 80rpx;
display: flex;
justify-content: center;
align-items: center;
}
.picker-item-child-label {
font-size: 28rpx;
}
</style>
```
在上面的代码中,我们定义了一个`scroll-view`组件,并使用`v-for`循环生成选项。每个选项都包含一个`label`和`value`属性,以及一个`children`数组,用于表示该选项下的子选项。
通过绑定`showChildren`属性来控制子选项的显示与隐藏。通过点击父选项来切换子选项的显示与隐藏,通过点击子选项来获取选中的值,并将`showChildren`属性设置为`false`,隐藏子选项。
最后,我们对样式进行了简单的处理,使其能够在`scroll-view`组件中正常滑动。
阅读全文