如何使用VueJS限制未登录用户的页面访问?

问题描述 投票:0回答:2

我目前正在练习 VueJs 并制作一些示例应用程序。我正在制作一个非常简单的应用程序,它基本上只是一个登录页面,用户将在其中放置他们的凭据并访问他们的个人资料。但是,如果用户未登录(即他们尝试通过手动将 url 更改为 /profile 来访问),我想不出一种方法来限制对个人资料部分的查看。

该应用程序非常简单,它只是使用 JS 和 bootstrap。

如果用户未登录并尝试访问个人资料页面,是否可以立即将用户重定向回登录屏幕?

javascript vue.js single-page-application vue-router
2个回答
8
投票
您可以使用

https://router.vuejs.org/guide/advanced/navigation-guards.html beforeEach

 检查当前用户是否已登录并执行您需要执行的操作:)。

您的路线:

... { path:'/profile', meta:{guest:false}, component:ProfileComponent }, ...

示例:

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(); });
    

4
投票
如果您只有少数需要保护的路由,您也可以使用

beforeEnter

 参数。

routes.js import {ifAuthenticated} from "../middleware/authentication"; { path: '/test', name: 'Test', component: 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 } }) }) }

vuex 的使用示例。

© www.soinside.com 2019 - 2024. All rights reserved.