vue-router 路由
快速开始
-
创建路由对象
// ./router/index.js import { createRouter, createWebHashHistory } form 'vur-router'; // 路由的两种模式 // import { craeteWebHistory} from 'vue-router'; const router = createRouter();
// 引入组件 import Home from '../views/Home.vue'; import About from '../views/About.vue'; const router = createRouter({ // 映射 routes: [ { path: '/', redirect: '/home' }, { path: '/home', component: Home }, { path: '/about', component: About } ] })
添加
history
字段const router = createRouter({ // 指定模式 history: createWebHashHistory(), // 映射 routes: [ { path: '/', redirect: '/home' }, { path: '/home', component: Home }, { path: '/about', component: About } ] })
-
main.js 中注册router
// main.js
import router from './router';
app.use(router);
<template>
<div id="app">
<h2>App</h2>
<div class="nav">
<router-link to="/home">首页</router-link>
<router-link to="/about">关于</router-link>
</div>
<router-view></router-view>
</div>
</template>
router-link
-
to 属性
字符串或对象
<router-link :to="{ path: '/home' }">首页</router-link>
<router-link to="/home">首页</router-link>
-
replace 属性
设置该属性时,调用
router.replace()
,而不是router.push()
-
active-class
属性设置激活后的
a
元素应用的class, 默认是router-link-active
路由懒加载
将组件引入写成函数形式,即需要时调用才引入,加快了加载时间。
// 原引入
// import Home from '../views/Home.vue';
// import About from '../views/About.vue';
// 路由的懒加载
// /* webpackChunkName: 'name'*/ 为webpack打包提供包名
const Home = () => import(/* webpackChunkName: 'home' */"../views/About.vue");
const About = () => import(/* webpackChunkName: 'about' */"../views/Home.vue");
// 直接加入路由中 routes 字段
routes: [
{ path: '/', redirect: '/home' },
{ path: '/home', component: () => import("../views/Home.vue") },
{ path: '/about', component: () => import("../views/About.vue") }
]
获取动态路由的值
- 在
template
中,直接使用$router.params
获取值
<template>
<div class="user">
<!-- 在模板中获取id -->
<h2>User: {{ $route.params.id }}</h2>
</div>
</template>
- 在
setup
中,使用 vue-router 中提供的 hook:useRoute
- 该 Hook 返回一个route对象,对象中保存当前路由相关值
- 在
created
中,通过this.$route.params
获取值
NotFound
即没有找到匹配的路由展示的页面。
{
// 没有匹配的路由,在 routes 字段添加 path, 展示NotFound.vue
path: '/:pathMatch(.*)',
component: () => import("../views/NotFound.vue")
}
嵌套路由
使用 children
字段。
{
name: 'home',
path: '/home',
component: () => import("../views/Home.vue"),
meta: { name: "home", date: 18 },
children: [
{
path: '/home',
redirect: '/home/recommend',
},
{
path: 'recommend',
component: () => import("../views/HomeRecommend.vue")
},
{
path: 'ranking',
component: () => import("../views/HomeRanking.vue")
}
]
},
编程式导航
在 vue2 中跳转路由
jumpToprofile() {
// this.$router.push('/profile');
this.$router.push({
path: '/profile',
// query 表示传递的参数
query: {
name: 'param',
age: 12
}
})
}
在 vue3 中跳转路由
import { useRouter } from 'vue-router';
// 拿到当前正在使用的路由
const router = useRouter();
const jumpToProfile = () => {
// router.push('/profile');
router.push({
path: '/profile',
query: {
name: 'param',
age: 12
}
})
// router.back();
// router.forward();
// router.go();
}
动态添加路由
使用 router.addRoute()
传入一个路由对象。
// 动态添加 vip 页面
let isAdmin = true;
if (isAdmin) {
router.addRoute({
path: '/admin',
component: () => import("../views/Admin.vue")
})
}
// home 为上一级路径
router.addRoute("home", {
path: 'vip',
component: () => import("../views/HomeVip.vue")
})
路由导航守卫
vue-router 提供的导航守卫主要用来通过跳转或取消的方式守卫导航
全局的前置守卫 beforeEach
是在导航触发时会被回调的:
参数:
to
: 即将进入的路由Route 对象from
: 即将离开的路由Route对象
返回值:
false
:取消当前导航- 不返回或 undefined : 进行默认导航
- 返回一个路由地址:
- 可以使一个 string 类型的路径
- 可以使一个对象,对象中包含 path、query、params 等信息;
参数三 next :
- 在 vue2 中使用next 函数来决定如何进行跳转
- 但在 vue3 中通过返回值来控制,不推荐使用next函数,因为开发中很容易调用多次next;
路由解析流程
- 导航被触发
- 在失活的组件里调用
beforeRouteLeave
守卫 - 调用全局的
beforeEach
守卫 - 在重用的组件里调用
beforeRouteUpadate
- 在路由配置里调用
beforeEnter
- 解析异步路由组件
- 在被激活组件中调用
beforeRouteEnter
- 调用全局的
beforeResolve
- 导航被确认
- 调用全局
afterEach
钩子 - 触发 DOM 更新
- 调用
befroeRouteEnter
守卫中传给 next 的回调函数,创建好的最简实例会作为回调函数的参数传入