admin管理员组文章数量:1242791
I'm currently practicing VueJs and making some sample apps. I'm making a very simple app that is basically just a login page where users will put their credentials and access their profile. However, I can't think of a way to restrict view to the profile section if the user isn't logged (i.e that they try to access by manually changing the url to /profile)
The app is pretty barebones, it's just using JS and bootstrap.
Is there a way to immediately redirect users back to the login screen if they're not logged and try to access the profile page?
I'm currently practicing VueJs and making some sample apps. I'm making a very simple app that is basically just a login page where users will put their credentials and access their profile. However, I can't think of a way to restrict view to the profile section if the user isn't logged (i.e that they try to access by manually changing the url to /profile)
The app is pretty barebones, it's just using JS and bootstrap.
Is there a way to immediately redirect users back to the login screen if they're not logged and try to access the profile page?
Share Improve this question edited Mar 30, 2024 at 16:45 nbro 15.9k34 gold badges119 silver badges213 bronze badges asked Sep 28, 2018 at 17:15 DasphillipbrauDasphillipbrau 5823 gold badges11 silver badges20 bronze badges 02 Answers
Reset to default 8You can use https://router.vuejs/guide/advanced/navigation-guards.html beforeEach
to check if the current user is logged or not and do what you need to do :).
your routes:
...
{
path:'/profile',
meta:{guest:false},
ponent:ProfileComponent
},
...
example :
router.beforeEach((to, from, next) => {
if (!to.meta.guest) {
// check if use already logged
// if true then go to home
return next({path:'/'}); // '/' is home page for example
// else then continue to next()
}
return next();
});
You can use also beforeEnter
param if you have only few routes which should be protected.
routes.js
import {ifAuthenticated} from "../middleware/authentication";
{
path: '/test',
name: 'Test',
ponent: Test,
beforeEnter: ifAuthenticated
},
authentication.js
import store from '../../store'
export const ifAuthenticated = (to, from, next) => {
store.dispatch('User/getUser')
.then(() => {
next()
})
.catch(() => {
next({ name: 'Login', query: { redirect_to: to.fullPath } })
})
}
Example with usage of vuex.
本文标签: javascriptHow to restrict page access to unlogged users with VueJSStack Overflow
版权声明:本文标题:javascript - How to restrict page access to unlogged users with VueJS? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1740164123a2234975.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论