目录
[1.1. 基于语法](#1.1. 基于语法)
[1.2. 主要代码](#1.2. 主要代码)
[2.1. 声明式导航类名匹配方式](#2.1. 声明式导航类名匹配方式)
[2.2. 声明式导航类名样式自定义](#2.2. 声明式导航类名样式自定义)
[2.3. 核心代码](#2.3. 核心代码)
一、导航高亮
1.1. 基于语法
在Vue中通过VueRouter插件,我们可以非常简单的实现实现导航高亮效果
VueRouter 提供了一个全局组件 router-link (取代 a 标签)
① 能跳转,配置 to 属性指定路径(必须) 。
,但是to标签中填写的路径无需 #
a标签的写法:

router-link写法:

② 能高亮,默认就会提供高亮类名,可以直接设置高亮样式

我们通过开发者工具可以看到,router-link的本质还是 a 标签

1.2. 主要代码
html
<template>
<div>
<div class="footer_wrap">
<router-link to="/find">发现音乐</router-link>
<router-link to="/my">我的音乐</router-link>
<router-link to="/friend">朋友</router-link>
</div>
<div class="top">
<!-- 路由出口 → 匹配的组件所展示的位置 -->
<router-view></router-view>
</div>
</div>
</template>
<script>
export default {};
</script>
<style>
body {
margin: 0;
padding: 0;
}
.footer_wrap {
position: relative;
left: 0;
top: 0;
display: flex;
width: 100%;
text-align: center;
background-color: #333;
color: #ccc;
}
.footer_wrap a {
flex: 1;
text-decoration: none;
padding: 20px 0;
line-height: 20px;
background-color: #333;
color: #ccc;
border: 1px solid black;
}
.footer_wrap a:hover {
background-color: #555;
}
</style>
二、声明式导航的两个类名
2.1. 声明式导航类名匹配方式
我们发现 router-link 自动给当前导航添加了 两个高亮类名
① router-link-active 模糊匹配 (用的多)
to="/my" 可以匹配 /my /my/a /my/b ....
② router-link-exact-active 精确匹配
to="/my" 仅可以匹配 /my

2.2. 声明式导航类名样式自定义
我们已经看到router-link默认给我们添加了两个高亮类名,所以我们可以通过修改这两个类名的样式属性,来自定义修改高亮的颜色及其他样式效果:
2.3. 核心代码
其余代码不变,照搬前面的即可
App.vue
html
<template>
<div>
<div class="footer_wrap">
<router-link to="/find">发现音乐</router-link>
<router-link to="/my">我的音乐</router-link>
<router-link to="/friend">朋友</router-link>
</div>
<div class="top">
<!-- 路由出口 → 匹配的组件所展示的位置 -->
<router-view></router-view>
</div>
</div>
</template>
<script>
export default {};
</script>
<style>
body {
margin: 0;
padding: 0;
}
.footer_wrap {
position: relative;
left: 0;
top: 0;
display: flex;
width: 100%;
text-align: center;
background-color: #333;
color: #ccc;
}
.footer_wrap a {
flex: 1;
text-decoration: none;
padding: 20px 0;
line-height: 20px;
background-color: #333;
color: #ccc;
border: 1px solid black;
}
.footer_wrap a.router-link-active {
background-color: purple;
}
.footer_wrap a:hover {
background-color: #555;
}
</style>