改一下vue和原生微信小程序就能用,通用的。
<template>
<view class="tree" v-if="lists.length">
<view class="item" v-for="item in lists">
<view class="title" @click="curShow(item)">
{{ item.name }}
<b :class="item.flag?'down':'up'">^</b>
</view>
<!-- 这里是关键-->
<view class="p_item" :style="{maxHeight:item.flag ? maxHeight : 0}">
<view id="p-list-inner">
<view class="sub-x" v-for="sub in item.sublists">
{{ sub.name }}
</view>
</view>
</view>
</view>
</view>
</template>
<script>
export default {
name: "classDetail",
data() {
return {
lists: [],
maxHeight: 0
}
},
mounted() {
// 模拟后台返回数据
setTimeout(() => {
this.lists = [
{
name: "运动服务",
flag: false,
sublists: [
{name: "运动服务1"},
{name: "运动服务1"},
{name: "运动服务1"},
{name: "运动服务1"},
]
},
{
name: "家电家具",
flag: false,
sublists: [
{name: "家电家具1"},
{name: "家电家具1"},
{name: "家电家具1"},
{name: "家电家具1"}
]
},
{
name: "衣服包包",
flag: false,
sublists: [
{name: "衣服包包1"},
{name: "衣服包包1"},
{name: "衣服包包1"},
{name: "衣服包包1"}
]
},
{
name: "日常百货",
flag: false,
sublists: [
{name: "日常百货1"},
{name: "日常百货1"},
{name: "日常百货1"},
{name: "日常百货1"}
]
},
{
name: "日常百货",
flag: false,
sublists: [
{name: "日常百货1"},
{name: "日常百货1"},
{name: "日常百货1"},
{name: "日常百货1"}
]
}
]
}, 2000)
},
methods: {
// 获取dom
getRect(context, selector) {
return new Promise((resolve) => {
const query = uni.createSelectorQuery().in(context);
query
.select(selector)
.boundingClientRect((data) => {
resolve(data);
})
.exec();
});
},
// 展开当前点击项
curShow: function (item) {
this.getRect(this, '#p-list-inner').then(res => {
item.flag = !item.flag;
//取反来控制一级选项的显示与隐藏
this.maxHeight = res.height + 'px'
})
}
},
}
</script>
<style scoped>
.tree {
margin: 0 auto;
width: 150px;
background-color: #0088CC;
color: white;
font-size: 16px;
}
.title {
position: relative;
border: 1px solid;
}
b {
position: absolute;
transition: all ease 0.6s;
top: 50%;
right: 0;
margin-top: -10px;
}
b.up {
transform: rotate(0deg);
}
b.down {
transform: rotate(180deg);
}
.p_item {
overflow: hidden;
transition: max-height 0.4s ease;
}
.sub-x {
background-color: rgba(0, 0, 0, 0.6);
border: 1px solid;
}
</style>