在真实的Vue应用程序中,路由器可以轻松达到数百行的长度,因此我将router.js
拆分为单独的(组件)路由文件,并将其导入到index.js
中。这样做,我破坏了beforEach
函数,并且无法弄清楚如何将身份验证保护与重构代码一起使用。
下面的beforeEach
抛出使用实现:
未捕获的TypeError:routes.beforeEach不是函数
任何有关示例的帮助将不胜感激!
我的路线index.js:
import Vue from 'vue';
import Router from "vue-router";
import firebase from 'firebase'
// BASE ROUTES
import {
. . .
aBunch,
ofRoutes,
. . .
} from '@/routers/base'
// INVENTORY ROUTERS
import {
. . .
aBunch,
more,
routes,
. . .
} from '@/routers/inventory'
Vue.use(Router);
const baseRoute = [
{
path: '*',
redirect: '/login'
},
{
path: '/',
redirect: '/login'
},
{
path: '/login',
name: 'login',
component: load('Login'),
meta: { transitionName: 'slide' },
},
{
path: '/sign-up',
name: 'sign up',
component: load('Signup'),
meta: { transitionName: 'slide' },
},
]
const routes = baseRoute.concat(
. . .
concat,
aBunch,
ofRoutes,
. . .
);
function load (component) {
return () => import(
/* webpackChunkName: "[request]" */
`@/views/${component}.vue`
)
}
routes.beforeEach((to, from, next) => {
let currentUser = firebase.auth().currentUser
let requiresAuth = to.matched.some(record => record.meta.requiresAuth)
if (requiresAuth && !currentUser) next('login')
else if (!requiresAuth && currentUser) next('dashboard')
else next()
})
export default new Router({
mode: 'history',
base: process.env.BASE_URL,
routes,
});
答案 0 :(得分:1)
beforeEach在路由器上。
let router = new Router({
mode: 'history',
base: process.env.BASE_URL,
routes,
})
router.beforeEach((to, from, next) => {
let currentUser = firebase.auth().currentUser
let requiresAuth = to.matched.some(record => record.meta.requiresAuth)
if (requiresAuth && !currentUser) next('login')
else if (!requiresAuth && currentUser) next('dashboard')
else next()
})
export default router
如果您还希望将beforeEach放入其自己的文件中,则可以将构建的路由器导入另一个文件中并在其中调用
import Router from "@/router"
export default () => {
Router.beforeEach( .... );
}