嵌套路由的基础配置配置
route.js 文件
import Vue from "vue";
import Router from "vue-router";
Vue.use(Router);
const originalPush = Router.prototype.push;
Router.prototype.push = function push(location) {
return originalPush.call(this, location).catch((err) => err);
};
export default new Router({
routes: [
{
name: 'test',
path: '/test',
component:()=>import(/* webpackChunkName:"test" */"test/test.vue")
children: [
{
name: 'subTest',
path: 'subTest',
}
]
}
],
});
test.vue 文件
<template>
<div>
<router-view></router-view>
</div>
</template>
注意事项
-
const originalPush = Router.prototype.push;
Router.prototype.push = function push(location) {
return originalPush.call(this, location).catch((err) => err);
};
-
以上三行代码是用户防止用户重复点击相同路由报错,的拦截请求
-
在使用嵌套路由时,使用到了children,里面的path 是不能加 / 的 否则会到至路由切换不成功
-
component 引入组件的时候 需要加上 webpackChunkName 达到分包的效果
-
component 引入组件的时候 需要使用路由懒加载的模式,提高页面加载效率
路由嵌套的高级配置
将路由文件拆分为若干个不同模块的文件
index.js 文件
import Vue from "vue";
import Router from "vue-router";
import test from "./test/index"
Vue.use(Router);
const originalPush = Router.prototype.push;
Router.prototype.push = function push(location) {
return originalPush.call(this, location).catch((err) => err);
};
export default new Router({
routes: [
{
name: 'test',
path: '/test',
...test
}
],
});
.test.js 文件
export default {
component: () => import(/* webpackChunkName: "index" */ "test/index.vue"),
children: [
{
path: 'testPromise',
name: "testPromise",
component:()=>import(/* webpackChunkName:"testPromise" */"test/testPromise.vue")
}
]
}
- 先定义一个二级路由js文件,
- 在index.js 导入 test.js 文件,使用解构运算符将二级路由的数据引用到主路由中
路由元
import Vue from "vue";
import Router from "vue-router";
Vue.use(Router);
const originalPush = Router.prototype.push;
Router.prototype.push = function push(location) {
return originalPush.call(this, location).catch((err) => err);
};
export default new Router({
routes: [
{
name: 'test',
path: '/test',
children: [
{
name: 'subTest',
path: 'subTest',
meta: {
loginAuth:true
}
}
]
}
],
});
- meta是路由元,可以理解为对路由的标记,比如有如meta对象里有login:true 就表明这个路由是需要登录后才能进行跳转的
全局路由导航守卫
// 路由全局导航守卫
// const token = store.state.user.getToken
const token = ""
router.beforeEach((to, from, next) => {
if (to.meta.loginAuth) {//需要登录
if (token) {//
next();
} else {
next("/login")
}
} else {//不需要登录
next()
}
})
// 路由跳转之后的操作
router.afterEach((to, from, next) => {
document.title = to.meta.title
window.scrollTo(0, 0)
})
- router.beforeEach是全局的前置路由导航首位,在页面跳转之前进行判断
- router.beforeEach有三个参数 to 表示要跳转到哪个路由的信息对象,from表示 来自哪个路由next 进行下一步或者跳转到指定页面。
- 注意在router.beforeEach中跳转到指定页面需要用next() 方法跳转不能使用route.push
- router.afterEach 可用于 页面跳转之后的操作,如document.title 动态设置 页面的title,页面跳转后滚动到顶部