VueRouter, VueJS, and Laravel route guard



我想将应用程序的特定页面隐藏在安全层后面(简单的密码表单将向服务器发送请求以进行验证(。

基于Vuerouter的文档,我认为beforeEnter是合适的。但是,我不确定如何要求用户访问特定组件,然后成功进入密码,然后才能继续进行此当前路线。

有人有这样的例子吗?我很难找到类似的东西。

import Vue from 'vue';
import VueRouter from 'vue-router';
Vue.use(VueRouter);
const routes = [
  { path: '/test/:testURL', component: require('./components/test.vue'), 
    beforeEnter: (to, from, next) => {
           // somehow load another component that has a form
           // the form will send a request to Laravel which will apply some middleware
           // if the middleware successfully resolves, this current route should go forward. 
    }
  },
];
const router = new VueRouter({
  routes,
  mode: 'history',
});
const app = new Vue({
  router
}).$mount('#app');

假设您只想对选定的组件执行身份验证,则可以使用 theTERENTER ROUTE ROUTE guard。使用以下代码。

const routes = [
  { path: '/test/:testURL', component: require('./components/test.vue'), 
    beforeEnter:requireLogin
  },
];
function requireLogin(to, from, next) {
    if (authenticated) {
        next(true);
    } else {
        next({
            path: '/login',
            query: {
                redirect: to.fullPath
            }
        })
    }
}

此外,您可以在登录组件中创建一个登录屏幕和操作,以重定向到给定的重定向参数在设置 auth 身份验证变量之后。我建议您在Veux Store中维护身份验证变量

最新更新