为什么要使用 Vue-Router?
Vue Router 是 Vue.js 的官方路由。它与 Vue.js 核心深度集成,让用 Vue.js 构建单页应用变得轻而易举。
安装
npm i -S vue-router@4
新建 src/router/index.ts
import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";
export const asyncRoutes: Array<RouteRecordRaw> = [
{
path: "/",
//重定向到活动界面
redirect: "/activity",
meta: {
title: "首页", //配置title
keepAlive: false, //是否缓存
requireAuth: false, //是否需要身份验证
},
},
//活动中心
{
path: "/activity",
name: "activity",
//路由懒加载
component: () => import("@/views/activity/Activity.vue"),
},
//通过ID进入藏品详细
{
path: "/collectionDetails/:id",
name: "collectionDetails",
component: () => import("@/views/collection-details/CollectionDetails.vue"),
},
];
const router = createRouter({
// 始终滚动到顶部
scrollBehavior() {
return { top: 0 };
},
history: createWebHashHistory(),
routes: asyncRoutes,
});
export default router;
在 main.ts 全局中使用
import { createApp } from "vue";
import router from "./router/index";
const app = createApp(App);
app.use(router);
app.mount("#app");
在 App.vue 全局中使用
<template>
<div class="main">
<router-view></router-view>
</div>
</template>
核心概念与基本使用
history
在创建路由器实例时,
history配置允许我们在不同的历史模式中进行选择。
| 模式 | 说明 | 区别 | Nginx 配置 |
|---|---|---|---|
| Hash | createWebHashHistory() | 有#,不需要服务端配合 | 无 |
| HTML5 | createWebHistory() | 无#,需要服务端配合 | location / { try_files uri/ /index.html; } |
路由跳转
import { useRouter } from "vue-router";
const router = useRouter();
//不带参数
router.push("/");
//路由query传参
router.push({
path: "/",
query: {
name: "小龙",
},
});
//路由params传参
router.push({
path: "/",
params: {
name: "小龙",
},
});
路由接受参数
import { useRoute } from "vue-router";
const route = useRoute();
console.log(route.query.name); //小龙
console.log(route.params.name); //小龙
- query 更加类似于 get 传参,在浏览器地址栏中显示参数,刷新不会丢失数据
- params 则类似于 post 传参,在浏览器地址栏中不显示参数,刷新会丢失数据
重定向
{
path: "/",
//访问'/',重定向到'/activity'
redirect: "/activity",
},
当没有匹配到正确路由的时候,重定向/404
{
path: "/:pathMatch(.*)",
redirect: "/404",
},
导航守卫
通常用于检查用户是否有权限访问某个页面,验证动态路由参数,或者销毁监听器 自定义逻辑运行后,
next回调用于确认路由、声明错误或重定向vue-router 4.x中可以从钩子中返回一个值或Promise来代替
// to 将要访问的路径
// from 代表从哪个路径跳转而来
// next 是个函数,表示放行 next() 放行 next('/login') 跳转登录页面
router.beforeEach((to, from, next) => {
//设置浏览器标签页的标题
if (typeof to.meta.title === "string") {
document.title = to.meta.title;
}
// 如果用户访问的登录页,直接放行
if (to.path === "/login") return next();
//访问用户页面,兑换藏品
if (to.path === "/user") {
// 从 localStorage 中获取到保存的 token 值
const { token = "", idCardStatus } = storage.getItem("loginInfo") || {};
// 没有 token,强制跳转到登录页
if (!token) return next("/login");
//没有实名认证
if (idCardStatus === 0) return next("/realName");
next();
}
next();
});