【问题标题】:after mode: 'history' vue router doesn't work模式后:“历史”vue 路由器不起作用
【发布时间】:2018-02-16 13:14:37
【问题描述】:

我最近开始学习 vuejs,并使用 firebase 构建和应用以进行身份​​验证。 安装 webpack 主题并尝试删除链接上的默认主题标签后出现问题。当我插入mode:history 时,它不会在我登录到我的 hello 页面后重定向我。当我删除它时,一切正常。

我的 index.js(在我的 router 文件夹下):

Vue.use(Router)

const router = new Router({
  mode: 'history',
  routes: [
    {
      path: '*',
      redirect: '/login'
    },
    {
      path: '/',
      redirect: '/login'
    },
    {
      path: '/login',
      name: 'Login',
      component: Login
    },
    {
      path: '/sign-up',
      name: 'SignUp',
      component: SignUp
    },
    {
      path: '/hello',
      name: 'Hello',
      component: Hello,
      meta: {
        requiresAuth: true
      }
    }
  ]
})

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('hello')
  else next()
})

export default router

这是我的登录按钮示例:

<button class="btn" type="submit" v-on:click="signIn">Log In</button>

还有我的组件脚本:

<script>
  import firebase from 'firebase'

  export default {
    name: 'login',
    data: function() {
      return {
        email: '',
        password: ''
      }
    },
    methods: {
      signIn: function() {
        firebase.auth().signInWithEmailAndPassword(this.email, this.password).then(
          (user) => {
            this.$router.replace('hello')
          },
          (err) => {
            alert('Oops. ' + err.message)
          }
        );
      }
    }
  }
</script>

这和v-on:click函数有关系吗?

如果您需要其他任何东西来解决我的问题,请告诉我。

【问题讨论】:

  • 没关系,就像我之前提到的,当我删除历史模式时,一切正常
  • 请出示您的整个模板代码

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


【解决方案1】:

案件很重要!

替换

this.$router.replace('hello')

this.$router.replace('Hello')

也替换

next('login')

next('/login')

next('Login')

【讨论】:

  • 我应该把next('/login')放在哪里?
  • 这里 if (requiresAuth &amp;&amp; !currentUser) next('login') 和下一行
  • 我更新了答案。您需要通过名称或路径显式调用路由。案件很重要。
  • 您是否更改了所有实例?像下一个('你好')
  • 另外,您应该在登录实例中使用 .push 而不是 .replace。如果用户单击后退按钮,他们希望返回登录页面,而不是之前的任何页面。通常,在大多数情况下,“替换”并不是很好的用户体验。
猜你喜欢
  • 2016-07-24
  • 2020-08-14
  • 2018-09-13
  • 2021-09-27
  • 2018-07-29
  • 2020-01-27
  • 2021-06-03
  • 2018-10-02
  • 2018-07-07
相关资源
最近更新 更多