使用组件
elementplus 的 el-menu 组件 el-input 组件
要求
点击侧边栏菜单同时改变文章的上一篇下一篇字段,点击文章的上一篇下一篇改变侧边栏高亮
代码
侧边菜单部分
<el-menu
:default-openeds="[0]"
:default-active="activeIndex"
active-text-color="#000000"
@select="selectMenu">
<template v-for="(item, index) in childrenVo" :key="index">
<el-sub-menu :index="item.name">
<template #title>
<span>{{ item.name }}</span>
</template>
<el-menu-item
v-for="(childItem, childIndex) in item.childrenVo"
:index="childItem.name">
{{ childItem.name }}
</el-menu-item>
</el-sub-menu>
</template>
</el-menu>
default-active 是默认高亮的数据
childrenVo 就是侧边栏菜单的内容了
childrenVo: [
{
"id": 1,
"name": "平台介绍",
"childrenVo": [
{
"id": 4,
"name": "什么平台?",
},
{ "id": 5,
"name": "你猜",
}
]
},
{
"id": 2,
"name": "系统介绍",
"chilfrenVo": [
{
"id": 3,
"name": "什么系统?",
}
]
}
]
// 获取文章标题,并拿到对应的文章对象
selectMenu(articleName) {
// articleName 这个参数就是 el-sub-menu 设置的index,详见组件官网
//获取文章在数组中的位置
let index = this.articleList.indexOf(articleName);
// 判断位置,添加上一篇文章,下一篇文章的字段
// 判断第一篇文章
if (index == 0) {
this.previous = '暂无';
this.next = this.articleList[index + 1];
} else
// 判断最后一篇文章
if (index == this.articleList.length - 1) {
this.next = '暂无';
this.previous = this.articleList[index - 1];
} else {
this.next = this.articleList[index + 1];
this.previous = this.articleList[index - 1];
};
},
底部上一篇下一篇部分
<div>
<div @click="turnPrevious">
<span ref="previous">上一篇:{{ previous }}</span>
</div>
<div @click="turnNext">
<span>下一篇:{{ next }}</span>
</div>
</div>
previous: '暂无', // 上一篇
next: '你猜', // 下一篇
articleList: [], // 存放文章名字的数组
// 将所有文章名字放到一个数组中,这个需要在获取完侧边栏菜单后执行
getAllArticleName() {
this.childrenVo.map(item => {
item.childrenVo.map(items => {
this.articleList.push(items.name);
})
});
this.next = this.articleList[1];
},
// 点击上一篇
turnPrevious() {
let index = this.articleList.indexOf(this.previous);
// 判断第一篇文章
if (index == 0) {
this.previous = '暂无';
this.next = this.articleList[1];
} else
// 如果没拿到文章,什么也不做
if (index == -1) {
return
} else
// 正常情况
{
this.next = this.articleList[index + 1];
this.previous = this.articleList[index - 1];
};
// 改变侧边栏高亮
this.changeActiveIndex(index);
},
// 点击下一篇
turnNext() {
// 拿到当前文章在文章列表中的索引
let index = this.articleList.indexOf(this.next);
// 判断最后一篇文章
if (index == this.articleList.length - 1) {
// 拿到对应的文章
this.next = '暂无';
this.previous = this.articleList[index - 1];
} else
// 如果没拿到文章,什么也不做
if (index == -1) {
return
} else
// 正常情况
{
this.next = this.articleList[index + 1];
this.previous = this.articleList[index - 1];
};
// 改变侧边栏高亮
this.changeActiveIndex(index);
},
// 将拿到的文章标题匹配成索引的形式,传值给 activeIndex 字段,展示高亮,需要把跳转的文章标题在articleList数组中的位置传进来
changeActiveIndex(index) {
if (this.previous == '暂无') {
this.activeIndex = this.articleList[0];
} else if (this.next == '暂无') {
this.activeIndex = this.articleList[this.articleList.length - 1];
} else {
// 排除两种特殊情况,正常情况
this.activeIndex = this.articleList[index]
}
},