【问题标题】:Vue router firebase auth guard doesn't workVue路由器firebase auth guard不起作用
【发布时间】:2018-12-15 07:23:28
【问题描述】:

我有一个简单的带有 firebase 身份验证的路由保护,但它不能正常工作。

以下代码不呈现任何内容,也不显示任何控制台错误。

所以,我现在没有在我的应用程序中实现任何身份验证系统,所以,它假设重定向到 /auth 路由并显示 Auth.vue 内容,但它不显示任何内容,只是一个空白页面。

知道如何解决它吗?

Auth.vue

<template>
  <div class="auth">
    <h1>Auth</h1>
  </div>
</template>

首页.vue

<template>
  <div class="home">
    <h1>Home</h1>
  </div>
</template>

路由器.js

import Vue from 'vue'
import Router from 'vue-router'
import Home from './views/Home.vue'
import Auth from './views/Auth.vue'
import firebase from 'firebase/app'
import 'firebase/auth'

Vue.use(Router)

let router = new Router({
  routes: [
    {
      path: '/',
      name: 'home',
      component: Home,
      meta: {
        auth: true
      }
    },
    {
      path: '/auth',
      name: 'auth',
      component: Auth
    }
  ]
});

router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.auth)) {
    firebase.auth().onAuthStateChanged(function(user) {
      if (!user) {
        next('/auth');
      } else {
        next();
      }
    });
  } else {
    next();
  }
});

export default router

【问题讨论】:

    标签: firebase vue.js vuejs2 firebase-authentication vue-router


    【解决方案1】:

    试试

    if(!user) { next({ path: '/auth' }) }

    而不是

    if (!user) { next('/auth'); }

    【讨论】:

    • 感谢回复,但也无济于事,路线没有改变,也没有任何渲染
    • 这就是我在当前项目中的方式router.beforeEach((to,from,next) =&gt; { if(to.matched.some(record =&gt; record.meta.auth)){ firebase.auth().onAuthStateChanged((user) =&gt; { if(!user) { next({ path: '/' }) } else { next() } })}else next() }) 你能告诉我你的 App.vue 吗?
    • @YegorGunko 好的,我在示例中看不到任何错误,您能否显示 main.js 文件,也许我在那里看到一些东西,因为路由器代码本身看起来不错。
    • @YegorGunko 好的,但是你在哪里初始化你的 firebase 连接?它应该看起来像这样this
    • 哦,对不起,我忘了用我的init导入firebase.js文件
    猜你喜欢
    • 2021-04-28
    • 1970-01-01
    • 2018-08-15
    • 2021-07-18
    • 2018-03-31
    • 2021-06-27
    • 1970-01-01
    • 1970-01-01
    • 2018-06-24
    相关资源
    最近更新 更多