六、实战开发 uni-app x 项目(仿京东)- 分类页
书接上回,我们来设计分类页,右键左侧项目管理器中的pages,在右键菜单选择新建页面
根据下面的图,设置相关内容
在左侧项目管理中,就会看到多出了category目录,目录下多出了category.uvue文件
修改category.uuvue文件
<template>
<view class="category">
<!-- 一级分类 -->
<scroll-view class="category-level1" scroll-y>
<view class="category-level1-item" v-for="(item, index) in categoryLevel1List" :key="index"
:class="{ active: activeLevel1Index === index }" @click="handleLevel1Click(index)">
<text>{
{ item.name }}</text>
</view>
</scroll-view>
<!-- 二级分类 + 商品列表 -->
<view class="category-content">
<!-- 二级分类 -->
<view class="category-level2">
<view class="category-level2-item" v-for="(item, index) in categoryLevel2List" :key="index"
:class="{ active: activeLevel2Index === index }" @click="handleLevel2Click(index)">
<text>{
{ item.name }}</text>
</view>
</view>
<!-- 商品列表 -->
<view class="goods-list">
<view class="goods-item" v-for="(item, index) in goodsList" :key="index">
<image :src="item.imageUrl" mode="aspectFill" />
<text class="goods-item-name">{
{ item.name }}</text>
<text class="goods-item-price">¥{
{ item.price }}</text>
</view>
</view>
</view>
</view>
</template>
<script>
export default {
data() {
return {
// 一级分类数据
categoryLevel1List: [
{ id: 1, name: '手机' },
{ id: 2, name: '电脑' },
{ id: 3, name: '家电' },
{ id: 4, name: '服饰' }
],
// 当前选中一级分类索引
activeLevel1Index: 0,
// 二级分类数据
categoryLevel2List: [],
// 当前选中二级分类索引
activeLevel2Index: 0,
// 商品列表数据
goodsList: []
};
},
methods: {
// 一级分类点击事件
handleLevel1Click(index) {
this.activeLevel1Index = index;
// 根据一级分类 id 获取二级分类数据
this.getCategoryLevel2List(this.categoryLevel1List[index].id);
},
// 二级分类点击事件
handleLevel2Click(index) {
this.activeLevel2Index = index;
// 根据二级分类 id 获取商品列表数据
this.getGoodsList(this.categoryLevel2List[index].id);
},
// 模拟获取二级分类数据
async getCategoryLevel2List(level1Id) {
// 模拟接口请求
const mockData = {
1: [
{ id: 11, name: '智能手机' },
{ id: 12, name: '老人手机' },
{ id: 13, name: '游戏手机' },
],
2: [
{ id: 21, name: '笔记本' },
{ id: 22, name: '台式机' },
{ id: 23, name: '平板电脑' }
],
3: [
{ id: 31, name: '冰箱' },
{ id: 32, name: '洗衣机' },
{ id: 33, name: '空调' }
],
4: [
{ id: 41, name: '男装' },
{ id: 42, name: '女装' },
{ id: 43, name: '童装' }
]
};
this.categoryLevel2List = mockData[level1Id] || [];
// 默认选中第一个二级分类
this.handleLevel2Click(0);
},
// 模拟获取商品列表数据
async getGoodsList(level2Id) {
// 模拟接口请求
const mockData = {
11: [
{ id: 111, name: 'iPhone 14', price: 5999, imageUrl: '