商品分类(三)-填充左侧菜单-一级菜单分类布局渲染&绑定active标签-选中菜单分类高亮显示 & 引用封装的less样式文件

it2025-12-07  11

左侧菜单渲染

实现左侧菜单布局进行数据填充控制菜单选中高亮 <div class="left"> <div :key='item.cat_id' v-for='item in listData' :class='["menu-item", currentIndex==item.cat_id?"active":""]'>{{item.cat_name}}</div> </div>

实例

左侧一级菜单-分类和单品类高亮显示

结构

高亮显示效果:采用flex布局,左边固定,右侧flex=1,宽度自定义

样式

在cate文件夹下,新建main.less文件,注意嵌套关系

.content { display: flex; position: fixed; left: 0; right: 0; top: 100rpx; bottom: 0; .left { height: 100%; width: 200rpx; flex-shrink: 0; overflow: auto; background: #eee; .menu-item { height: 102rpx; line-height: 102rpx; text-align: center; position: relative; } .active { background: #fff; color: red; &::before { content: ""; display: block; width: 4px; height: 60rpx; position: absolute; left: 0; top: 21rpx; background: red; } } } .right { flex: 1; height: 100%; overflow: auto; .brand-item { .brand-title { text-align: center; line-height: 2; } .brand-list { display: flex; flex-wrap: wrap; .brand { width: 33.33%; padding: 20rpx; box-sizing: border-box; img { width: 100%; height: 100rpx; } p { line-height: 1.5; font-size: 14px; text-align: center; } } } } } }

在cate/index.vue文件中,进行样式文件的导入

<style scoped lang="less"> @import './main.less'; </style>

左侧一级菜单更换成真实接口数据

注意:

第一种写法:

utils/request.js封装接口调用方法时,res指的是全部数据,还是只是data

methods: { async loadData () { // 调用接口获取分类数据 let data = await request('categories') this.cate = data } },

可能存在第二种写法:

打印res结果

此处已经获取到所有data,再用res进行层级数据处理就多余,故采用第一种写法

此时,一级菜单遍历如下,是写死的数据

更换一级分类活数据

一级菜单分类-显示效果

根据id(推荐)或索引值,增加一级菜单分类的控制高亮显示效果

export default { data () { return { //默认选中第一个 currentId: 1, cate: [] } }, }

动态绑定一级分类样式和高亮效果: 冒号+数组 格式

:class="['menu-item', {active: currentId === item.cat_id}]"

<!-- 左侧一级分类 --> <div class="left" @click='handleChange'> <div :data-id='item.cat_id' :key='item.cat_id' v-for='item in cate' :class="['menu-item', {active: currentId === item.cat_id}]"> {{item.cat_name}} </div> </div>

默认第一个被选中

左侧一级菜单-重点样式

.left { height: 100%; width: 200rpx; flex-shrink: 0; overflow: auto; background: #eee; .menu-item { height: 102rpx; line-height: 102rpx; text-align: center; position: relative; } //高亮效果样式 .active { background: #fff; color: red; &::before { content: ""; display: block; width: 4px; height: 60rpx; position: absolute; left: 0; top: 21rpx; background: red; } } } content: ""; display: block; width: 4px; height: 60rpx; position: absolute; left: 0; top: 21rpx; background: red; } } }
最新回复(0)