效果图如下所示:
一、左侧分类列表数据的获取和渲染
1、在data中定义分类数据节点:
data() {
return {
//分类数据列表
cateList:[]
}
},
2、调用获取分类列表数据的方法:
onLoad() {
//调用分类数据列表的方法
this.getCateList();
},
3、定义获取分类列表数据的方法:
//获取分类列表的数据
async getCateList() {
const { data: res } = await uni.$http.get('/api/public/v1/categories')
//请求失败
if (res.meta.status !== 200) {
return uni.$showMsg()
}else{
this.cateList = res.message
}
}
4、动态渲染左侧的一级分类列表
循环渲染列表结构以及动态添加active类名:
html:
<scroll-view class="left-scroll-view" scroll-y="true" :style="{height:wh + 'px'}">
<block v-for="(item,i) in cateList" :key="i">
<view :class="['left-scroll-view-item', i == active?'active':'']" @click="activeChange(i)">{{item.cat_name}}</view>
</block>
</scroll-view>
js
data() {
return {
//当前选中项的索引,默认让第一项被选中
active:0
}
},
二、右侧分类列表数据的获取和渲染
(一)、动态渲染右侧的二级分类列表
1、在 data 中定义二级分类列表的数据节点
data() {
return {
//二级分类列表
cateLevel2:[]
}
},
2、修改 getCateList 的方法,在请求到数据之后,为二级分类列表数据赋值;
async getCateList() {
const { data: res } = await uni.$http.get('/api/public/v1/categories')
if (res.meta.status !== 200) {
return uni.$showMsg()
}else{
this.cateList = res.message;
//为二级分类赋值
this.cateLevel2 = res.message[0].children;
}
},
3、修改 activeChange 方法,在一级分类选中项改变之后,为二级分类列表数据重新赋值;
activeChange(i) {
this.active = i;
//重新为二级分类赋值
this.cateLevel2 = this.cateList[i].children;
}
4、循环渲染右侧二级分类列表的UI结构
<!-- 右侧的滑动区域 -->
<scroll-view scroll-y="true" :style="{height:wh + 'px'}">
<view class="cate-lv2" v-for="(item2,i2) in cateLevel2" :key="i2">
<view class="cate-lv2-title">/ {{item2.cat_name}} /</view>
</view>
</scroll-view>
5、美化二级分类的标题样式
.cate-lv2-title {
font-size: 12px;
font-weight: bold;
text-align: center;
padding: 15px 0;
}
(二)、动态渲染右侧的三级分类列表
1、在 二级分类的<view>组件中,循环渲染三级分类的列表结构
<!-- 右侧的滑动区域 -->
<scroll-view scroll-y="true" :style="{height:wh + 'px'}">
<!-- 二级分类列表 -->
<view class="cate-lv2" v-for="(item2,i2) in cateLevel2" :key="i2">
<view class="cate-lv2-title">/ {{item2.cat_name}} /</view>
<!-- 三级分类列表 -->
<view class="cate-lv3-list">
<view class="cate-lv3-item" v-for="(item3,i3) in item2.children" :key="i3">
<image :src="item3.cat_icon" style="width: 60px;height: 60px;"></image>
<text>{{item3.cat_name}}</text>
</view>
</view>
</view>
</scroll-view>
2、美化三级分离的样式
.cate-lv3-list {
display: flex;
flex-wrap: wrap;
.cate-lv3-item {
width: 33.33%;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
margin-bottom: 10px;
image {
width: 60px;
height: 60px;
}
text {
font-size: 12px;
}
}
}