首页 文章

如何保护Vue.js中的客户端路由?

提问于
浏览
1

我正在 Build 一个水疗中心,它使用Vue.js作为前端框架,它与一个使用jsonwebtokens的纯json后端对话 . 我对React生态系统更熟悉 . 我目前还不确定如何保护Vue.js中的客户端路由 . (不是我对框架的决定 . 我是新雇员 . 是的!)

作为反应,我会做这样的事情 . 在项目的index.js文件中 . 在应用程序安装之前,检查localstorage中是否存在jsonwebtoken . 如果有,请将redux状态设置为登录 . 如果未设置为注销 .

然后我会使用更高阶的组件来保护我的路由,以便每当用户尝试进入客户端保护路由时,我会使用componentWillMount生命周期方法来检查登录状态 . 如果登录则渲染组件 . 否则重定向到登录页面 .

似乎vue中的高阶组件无法实现相同的行为 . 或者我只是找不到向我展示如何实现它的文档 . 有人可以与我分享他们如何解决这个问题吗?

3 回答

  • 1

    documentation中所述,您可以在要检查身份验证的所有路由上使用 meta feilds

    文档中提供的示例:

    router.beforeEach((to, from, next) => { 
        if (to.matched.some(record => record.meta.requiresAuth)) { 
            // this route requires auth, check if logged in 
            // if not, redirect to login page. 
            if (!auth.loggedIn()) { 
                next({ 
                    path: '/login', 
                    query: { redirect: to.fullPath } 
                }) 
            } else { 
                next() 
            } 
        } else { 
            next() // make sure to always call next()! 
        } 
    })
    

    或者对于组件导航保护,您可以按照wostex提供的第二个链接

  • 0

    我想我错过了路线元领域的文档 . 我做了一些愚蠢的事情,但我认为工作 . 哈哈 .

    router.beforeEach((to, from, next) => {
        let web = ["home", "login", "verifyAccount", "resetPassword","forgotPassword","register"];
        if(web.includes(to.name)){
            next();
        }else{
            axios.post('/api/auth/verify-token',{
                token: localStorage.token
            }).then(response=>{
                if(response.data.verification === true){
                    next();
                }else{
                    router.push({
                        name:'home',
                        params:{
                            serverError:true,
                            serverMsg: 'Please login to continue.'
                        }
                    });
                }
            }).catch(response=> {
                console.log(response);
            });
        }
    });
    
  • 3

    这是使用Vue.js进行auth实现的一个很好的例子:link

    更具体地说,这里是关于导航的手册 . 警卫:link

相关问题