文章目录
3.6 路由高亮
Vue3
可以通过如下的两种方式,将激活的路由链接进行高亮显示:
① 使用默认的高亮 class 类
② 自定义路由高亮的 class 类
3.6.1 默认的高亮 class 类
被激活的路由链接,默认会应用一个叫做 router-link-active 的类名。开发者可以使用此类名选择器,为激活的路由链接设置高亮的样式:
/*在index.css全局样式表中,重新router-link-active 的样式*/
.router-link-active {
background-color : red;
color : white;
font-weight: bold;
}
3.6.2 自定义路由高亮的 class 类
在创建路由的实例对象时,开发者可以基于 linkActiveClass 属性,自定义路由链接被激活时所应用的类名:
// 从 vue-router 中按需导入两个方法
import { createRouter, createWebHashHistory } from 'vue-router'
import Home from './MyHome.vue'
import Movie from './MyMovie.vue'
import About from './MyAbout.vue'
// 创建路由对象
const router = createRouter({
// 指定路由的工作模式
history: createWebHashHistory(),
// 自定义路由高亮的 class 类
//指定被激活的路由链接,会应用 active-router 这个类名,
//默认的router-link-active类名会被覆盖掉
linkActiveClass: 'active-router',
// 声明路由的匹配规则
routes: [
{ path: '/', redirect: '/home' },
{ path: '/home', component: Home },
{ path: '/movie', component: Movie },
{ path: '/about', component: About },
],
})
// 导出路由对象
export default router
3.7 命名路由
通过 name 属性为路由规则定义名称的方式,叫做命名路由。
// 动态路由匹配
{ name: 'mov', path: '/movie/:mid', component: Movie, props: true },
// 创建路由对象
const router = createRouter({
// 指定路由的工作模式
history: createWebHashHistory(),
// 自定义路由高亮的 class 类
linkActiveClass: 'active-router',
// 声明路由的匹配规则
routes: [
{ path: '/', redirect: '/home' },
{ path: '/home', component: Home },
// 动态路由匹配
{ name: 'mov', path: '/movie/:mid', component: Movie, props: true },
{
path: '/about',
component: About,
// 嵌套路由的重定向
redirect: '/about/tab1',
// 通过 children 属性嵌套声明子级路由规则
children: [
{ path: 'tab1', component: Tab1 },
{ path: 'tab2', component: Tab2 },
],
},
],
})
注意:命名路由的 name 值不能重复,必须保证唯一性!
3.7.1 使用命名路由实现声明式导航
为 <router-link>
标签动态绑定 to 属性的值,并通过 name 属性指定要跳转到的路由规则。期间还可以用params 属性指定跳转期间要携带的路由参数。
<router-link :to="{ name: 'mov', params: { mid: 2 } }">go to movie</router-link>
3.7.2 使用命名路由实现编程式导航
调用 push 函数期间指定一个配置对象,name 是要跳转到的路由规则、params 是携带的路由参数。
<template>
<div>
<h3>MyHome 组件</h3>
<router-link :to="{ name: 'mov', params: { mid: 2 } }">go to movie</router-link>
<button type="button" class="btn btn-primary" @click="goToMovie(1)">go to movie</button>
</div>
</template>
<script>
export default {
name: 'MyHome',
methods: {
goToMovie(id) {
this.$router.push({
name: 'mov',
params: {
mid: id,
},
})
},
},
}
</script>
<style lang="less" scoped></style>
Movie.vue
<template>
<div>
<h3>MyMovie 组件 --- {{ $route.params.mid }} --- {{ mid }}</h3>
</div>
</template>
<script>
export default {
name: 'MyMovie',
props: ['mid'],
}
</script>
<style lang="less" scoped></style>