项目场景:
VueRouter
需求描述
我写的是PC端,是这样的我的login页面有两种登录方式一种是商家登录,一种是用户登录,我点击商家登录,登录成功后跳转到商家路由配置的home首页, 然后我URL去访问用户登录路由配置仍然可以访问成功,这并不是我想要的效果,我要将他们分隔不能互相访问,因为他们本身就是两个身份。
思路方法:
我的想到的实现方法有两种
1.是这样的我的路由拦截是brforEach内路由白名单方法进行的拦截,方法是通过if判断在配置一个路由拦截,很显然这个方法对我来说只能想到开头,但想不到中间,想不到末尾
2.将routes内商家的路由配置抽离出来,然后在封装一个routes注意这里肯定重名了名字换一下,然后分别将他们命名为 商家 merchantRoutes 和 用户 userRoutes ,然后来到login vue文件,当点击商家登录时给vuex state内属性赋值为false,当点击用户登录时给vuex state内属性赋值为true,然后来到router/index.js嘛,然后三元判断当 state内属性为true时就 merchantRoutes否则userRoutes然后赋值给 const routes ,这样基本实现了!但是还有点小BUG就是在登录成功后切换了他不会立即生效 也不是立即 就是不生效,必须刷新页面后才能生效,这里不能直接添加 刷新,因为快和慢的问题,必须router.push执行后刷新才行,我刚开始首先想到是setTImeout,这个很显然是不行,后面bing了一下,使用router.push( '',()=>{})第二个参数,在二个参数内执行刷新。
然后上面的代码优化一下,把 merchantRoutes 商家路由配置抽离到外面文件 import引入一下来使用,基本完成了,但总感觉登录成功后刷新不好 ^_^,
需求实现:
import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store/index'
import { merchantRouter } from '@/routes/index'
Vue.use(VueRouter)
const userRoutes = [
{
path: '/login',
component: () => import('../views/login/index.vue'),
meta: {
title: '登录'
}
},
{
path: '*',
component: () => import('../views/Inexistence/index.vue'),
meta: {
title: '404'
}
},
{
path: '/',
component: () => import('../views/Layout/index.vue'),
redirect: '/home',
children: [
{
path: '/home',
component: () => import('@/views/home/index.vue'),
meta: {
title: '首页'
}
}
]
}
]
const isMerchantLoggedIn = store.state.Router.RouterMode
const routes = isMerchantLoggedIn ? userRoutes : merchantRouter
const router = new VueRouter({
routes,
mode: 'hash'
})
export default router
routes/index.js
export const merchantRouter = [
{
path: '/login',
component: () => import('../views/login/index.vue'),
meta: {
title: '登录'
}
},
{
path: '*',
component: () => import('../views/Inexistence/index.vue'),
meta: {
title: '404'
}
},
{
path: '/',
component: () => import('@/views/ULayout/index.vue'),
redirect: '/uhome',
children: [
{
path: '/uhome',
component: () => import('@/views/UHome/index.vue'),
meta: {
title: '首页'
},
key: 'uhome'
}
]
}
]
其他补充:
我之前还企图想将商家登录成功后 router赋值为 history ,用户登录成功后 router 赋值为hash,
router.meta = 'hash' ,以这样的方式分别赋值的
基本功能是实现了但有BUG就是页面刷新成功后 浏览器URL路径后会有 #/ ,是这个样子 http://localhost:8080/login#/ ,每次刷新都会出现最终放弃了!