采用计算属性监听跳转页面后url拼接的路由路径来判断是否在当前页面(包括解决嵌套路由带来的判断干扰)
效果图:
- 定义路由
router.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import Layout from '@/layout/index' // 布局(这是官网的布局采用的上中下布局模式)
// 把这段代码直接粘贴到router/index.js中的Vue.use(VueRouter)之前,解决重复点击当前路由导致的路由沉积控制台报错问题
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function (location) {
return originalPush.call(this, location).catch(err => { })
};
Vue.use(VueRouter)
const routes = [
path: '/',
component: Layout,
redirect: 'noRedirect', // 重定首页
name: 'layout',
children: [ // 嵌套路由
{
path: 'tinymce',
component: () => import('@/views/components-demo/tinymce'),
name: 'TinymceDemo',
meta: { title: 'Tinymce' }
},
{
path: 'markdown',
component: () => import('@/views/components-demo/markdown'),
name: 'MarkdownDemo',
meta: { title: 'Markdown' }
},
{
path: 'json-editor',
component: () => import('@/views/components-demo/json-editor'),
name: 'JsonEditorDemo',
meta: { title: 'JSON Editor' }
children: [ // 第二层级嵌套
{
path: 'json-editor/menu1', // 在定义嵌套路由的时候一定要把父路由的路由名加拼接上,后面导航页面需要筛选判断
component: () => import('@/views/nested/menu1'),
name: 'Menu1',
meta: { title: 'Menu 1' }
},
{
path: 'json-editor/menu2',
component: () => import('@/views/nested/menu2'),
name: 'Menu2',
meta: { title: 'Menu 2' }
}
]
},
]
- html+js部分(没加样式 主要是js)
<!-- 中间导航栏 -->
<template>
<div class="navigation">
<div
class="navigation-son"
v-for="(item, index) in navigationList"
:key="index"
>
<span
:class=" // 动态定义类
isSelect.split('/').includes(item.path.replace('/', '')) // 判断当前点击路由地址和url地址栏后的地址是否是相同,相同就添加样式类,不相同就赋值为空
? 'active'
: ''
"
@click="onSkip(item.path)"
>{{ item.title }}</span
>
</div>
</div>
</template>
export default {
name: "",
data() {
return {
navigationList: [ // 定义好需要切换的路由数组
{ title: "首页", path: "/tinymce" },
{ title: "企业服务", path: "/markdown" },
{ title: "软件产品", path: "/json-editor" },
],
};
},
computed: {
isSelect: { // 监听路由跳转
// getter
get() {
return this.$route.path;
},
// setter
set(val) {
this.$route.path = val;
},
},
},
mounted() {
/**
* 路由跳转回到顶部
*/
// chrome
document.body.scrollTop = 0;
// firefox
document.documentElement.scrollTop = 0;
// safari
window.pageYOffset = 0;
},
methods: {
onSkip(path) { // 点击切换页面
this.$router.push(path);
},
}
}
解释:
isSelect.split('/').includes(item.path.replace('/', '')) ? 'active' : ''
// 使用split把isSelect路劲字符串根据 '/' 拆分为数组,在获取循环当前点击的路由字符串使用 replace来替换里面的 '/'字段,在使用 includes 来判断数组里面是否存在和当前路由相同的值,布尔判断存在为真添加类名,否则class为空