项目四:后台用户管理系统(二):路由配置
好家伙,
路由配置还是比较复杂的
首先来看看项目的目录:
上代码:
index.js配置如下:
//当前项目的路由模块
//1.导入Vue和VueRouter的包
import Vue from "vue"
import VueRouter from "vue-router"
// import pathArr from "@/router/pathArr.js";
//导入需要的组件
import Login from "@/components/MyLogin";
import Home from "@/components/MyHome";
import Users from "@/components/menus/MyUsers";
import Rights from "@/components/menus/MyRights";
import Goods from "@/components/menus/MyGoods";
import Settings from "@/components/menus/MySettings";
import Orders from "@/components/menus/MyOrders";
import UserDetail from "@/components/user/MyUserDetail";
//2.新建pathArr数组
const pathArr= ['/home','/home/users']
//3.调用Vue.use()函数,把VueRouter安装为Vue插件
Vue.use(VueRouter)
//4.创建路由的实例对象
const router = new VueRouter({
routes: [
{path: '/',redirect: '/login'},
//登录路由规则
{path: '/login',component: Login},
//后台主页路由规则
{path: '/home',component: Home,redirect: '/home/users',children: [
{path: 'users',component: Users},
{path: 'rights',component: Rights},
{path: 'goods',component: Goods},
{path: 'settings',component: Settings},
{path: 'orders',component: Orders},
//用户详情页
{path: 'detail/:id',component: UserDetail}
]}
]
})
//5.设置路由守卫
router.beforeEach(function (to,f,next){
if (pathArr.indexOf(to.path) !== -1){
const token = localStorage.getItem('token')
if (token){
next()
}else {
next('/login')
}
}else {
next()
}
})
//6.向外共享路由的实例对象
export default router
拎两个点出来讲一下
1.子路由器嵌套
在这里我要实现一个用户详情页的功能, 效果如下
如果为每一个id都写一个路由,那么确实会有些麻烦
所以我们用一个id传值的方法
右边的红色框框中
{path: 'detail/:id',component: UserDetail}
路由规则中才能出现冒号,
而左边的路由跳转,用加号
gotoDetail(id) {
this.$router.push('/home/detail/'+id)
}
2.路由守卫设置
const pathArr= ['/home','/home/users']
router.beforeEach(function (to,f,next){
if (pathArr.indexOf(to.path) !== -1){
const token = localStorage.getItem('token')
if (token){
next()
}else {
next('/login')
}
}else {
next()
}
})
其中
pathArr.indexOf(to.path) !== -1
这句表示对数组(pahtArr)进行查找,
(pahtArr中的路由是我不希望用户在登陆前能够访问到的地址)
pathArr.indexOf(to.path) !== -1 这句话的意思是他的to.path在这个数组里面接下来执行下一步,
如果等于-1,那么就说明要去的地址不在pathArr数组中
(要去的地址可随意访问),
就不执行后续代码(不需要后续的"守卫检查")
路由配置大概是这些了(还有别的后续继续补充)