我正在尝试保护主页,如果用户未登录,则将其路由到登录页面。
为此,我制作了路由器对象,以便可以使用beforeEach()函数。
但是我得到这个错误:
当我尝试使路由器的对象不变时,会发生此错误。
router.js是:
import Vue from 'vue';
import Router from 'vue-router';
import firebase from 'firebase';
import Home from './views/Home.vue';
import Signup from './components/auth/Signup.vue';
import Login from './components/auth/Login';
Vue.use(Router);
const router = new Router({
mode: 'history',
base: process.env.BASE_URL,
routes: [
{
path: '/',
name: 'home',
component: Home,
meta: {
requiresAuth: true,
},
},
{
path: '/signup',
name: 'Signup',
component: Signup,
},
{
path: '/login',
name: 'Login',
component: Login,
},
],
});
// router guards
router.beforeEach((to, from, next) => {
// check to see if routh require auth
if (to.matched.some(rec => rec.meta.requiresAuth)) {
// check state of user
const user = firebase.auth().currentUser;
if (user) {
next();
} else {
next({ name: 'Login' });
}
} else {
next();
}
});
这是在main.js文件中。
import Vue from 'vue';
import firebase from 'firebase';
import router from './router';
import App from './App.vue';
Vue.config.productionTip = false;
const app = null;
// Wait for firebase init the user
firebase.auth().onAuthStateChanged(() => {
// init the app if not created
if (!app) {
new Vue({
router,
render: h => h(App),
}).$mount('#app');
}
});
答案 0 :(得分:1)
添加以下更改
将此行添加到router.js中的最后一行
export default router;
添加main.js
import router from './router';
(路径应指向您的router.js)
new Vue({
router,
....
....
})