VueJs拥有自己的路由器,所以我们不能实现中间件。取而代之的是,我们使用导航卫士来限制用户访问某些页面。我的项目有两个用户,一个是客户,另一个是工人。我不希望工作人员访问客户端的页面,也不希望客户端访问工作人员的页面。我现在面临的问题是如何在此处编写代码。阅读文档对我没有帮助。 这是我的来自routes.js的代码
const routes =[
{
path:'/login',
name: 'login',
component: Login
},
{
path:'/signup',
name:'signup',
component: Signup
},
{
path:'/user/dashboard',
name:'userdashboard',
component: Dashboard,
meta:{
requiredAuth: true,
client: true,
worker: false
}
},
{
path:'/verifyemail',
name:'verifyemail',
component: Verifyemail
},
{
path: '/logout',
name: 'logout',
component: Logout
},
{
path: '/worker/Dashboard',
name:'workerDashboard',
component: WorkerDashboard,
meta:{
requiredAuth: true,
client: false,
worker: true
}
}
];
const router = new Router({
routes,
mode: 'history'
});
router.beforeEach((to,from,next)=>
{
if(to.matched.some(record => record.meta.requiredAuth) && !Store.state.isLoggedIn )
{
next({name: 'login'});
return
}
if(to.path === '/login' && Store.state.isLoggedIn)
{
next({name:'userdashboard'});
return
}
if(to.path === '/signup' && Store.state.isLoggedIn)
{
next({name:'userdashboard'});
return
}
next()
});
在我的登录组件中
axios.post('http://127.0.0.1:8000/api/signin', { email: this.email, password: this.password}, { headers: { 'X-Requested-with': 'XMLHttpRequest' } })
.then((response) => {
const token = response.data.token;
localStorage.setItem('token', token);
this.loadinglogin = false;
store.commit('loginUser');
const UserType = response.data.userType;
if(UserType === '1'){
app.$router.push({name: 'userdashboard'});
}else if(UserType === '2'){
app.$router.push({name: 'workerDashboard'})
}else{
return 'not ok';
}
})
.catch((error) => {
console.log(error.response.data.error);
this.errored = true;
this.error= error.response.data.error;
this.loadinglogin = false
})
答案 0 :(得分:0)
不确定问题是什么,但是您可以从API中获取该组并将其放入您的商店中。然后添加一些吸气剂,检查beforeEach()
中的值并进行相应的重定向。例如:
const router = new VueRouter({
routes: [
{
path: '/foo',
component: Foo,
beforeEnter: (to, from, next) => {
if (!store.getters.isAdmin) {
next(false)
}
}
}
]
})
如@Tarasovych所述,此不能代替服务器端身份验证/授权。它只是增加了用户友好性。在返回任何数据之前,您仍然需要对每个请求进行身份验证/授权。