携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第17天,点击查看活动详情
一。路由设置
import Vue from "vue";
import VueRouter from "vue-router";
Vue.use(VueRouter);
浏览器加载动画
// npm i nprogress
// 导入NProgress
import NProgress from "nprogress";
// 导入nprogress样式
import "nprogress/nprogress.css";
定义一个路由数组
let routes = [
{
// 路由路径
path: "/home",
// 路由名称
name: "home",
// 路由组件
// 路由懒加载(进入首页快)
component: () => import("../components/Header.vue"),
// 路由元信息,其实就是一个对象,用于保存该路由的数据
meta: {
// 标题
title: "首页",
// 配置页面访问权限
role: [1, 2, 3],
},
// 二级路由
children: [
{
path: "nj",
component: () => import("../components/home/Njview.vue"),
},
{
path: "bj",
component: () => import("../components/home/Bjview.vue"),
},
{
path: "sh",
component: () => import("../components/home/Shview.vue"),
},
],
},
{
path: "/",
// 重定向,输入/地址后重定向到/home
redirect: "/home",
},
{
path: "/index",
redirect: "/home",
},
{
path: "/list",
name: "list",
component: () => import("../components/List.vue"),
meta:{
// 配置页面访问权限
role: [1, 2],
},
children: [
{
path: "/bc",
component: () => import("../components/list/Bcview.vue"),
},
{
path: "/bm",
component: () => import("../components/list/Bmview.vue"),
},
{
path: "/ad",
component: () => import("../components/list/Adview.vue"),
},
],
},
{
path: "/about",
name: "about",
component: () => import("../components/About.vue"),
meta:{
// 配置页面访问权限
role: [1, 3],
},
},
];
const router = new VueRouter({
// 配置路由数组
routes,
// 配置路由模式(有两种模式,history和hash)
// has采用锚链接原理,优点兼容性高,缺点有#号,不美观
// histroy模式采用H5最新的histroy API实现,优点没有#号,美观,缺点是比hash模式低一点,打包后的项目刷新后会丢失状态,需要在服务器中单独配置
// mode: "history",
// mode:"hash"(默认)
});
路由前置守卫
router.beforeEach((to, from, next) => {
// to到哪里去
// from从哪里来
//next 执行后放行
// 开启进度条动画(必须放行,否在无法加载)
NProgress.start();
// 放行
next();
// 获取浏览器缓存的信息(在main.js已经保存了)
let roleId = parseInt(sessionStorage.getItem("roleId"));
if (to.meta.role) {
if (to.meta.role.includes(roleId)) {
next();
} else {
alert("对不起,无法访问");
// NProgress.done();
}
} else {
next();
}
});
路由后置首位
router.afterEach((to, from) => {
// 关闭进度条动画
NProgress.done();
// 切换网页标题
document.title = to.meta.title;
});
导出路由
export default router;
二级路由
注意这里的路由路径,需要拼接父级的路由路径(exact-active-class高亮),需要拼接父级路由是因为当初在设置二级路由的时候前面没有带/
<p>
<router-link exact-active-class="active" to="/home/nj"
>南京</router-link
>
</p>
<p>
<router-link exact-active-class="active" to="/home/bj"
>北京</router-link
>
</p>
<p>
<router-link exact-active-class="active" to="/home/sh"
>上海</router-link
>
</p>
注意,子路由路径以/开头,在跳转路有时候前面不需要父级
<p>
<router-link exact-active-class="active" to="/bc"
>奔驰</router-link
>
</p>
<p>
<router-link exact-active-class="active" to="/bm"
>宝马</router-link
>
</p>
<p>
<router-link exact-active-class="active" to="/ad"
>奥迪</router-link
>
</p>