【问题标题】:How to stop component-loading and redirect in Vue?如何在 Vue 中停止组件加载和重定向?
【发布时间】:2018-02-27 12:56:52
【问题描述】:

我有一个非登录用户不能访问的组件。我在beforeCreate 钩子中实现了这个逻辑。问题是这并不能阻止组件继续加载,这是我想要的。

这是我的代码:

<script>
    export default {
        beforeCreate: function () {
            if (this.$root.auth.user === null) {
                this.$router.push({ name: 'auth.login' })
            }
        },

        mounted: function () {
            // some code that SHOULD NOT be processed
            // if the user isn't authenticated
        }
    }
</script>

我做错了什么?

【问题讨论】:

    标签: javascript vue.js vue-component vue-router


    【解决方案1】:

    您应该将 beforeCreate 函数移至路由器本身。 这是我的 Auth 捕获

    router.beforeEach(
      (to, from, next) => {
        if (to.matched.some(record => record.meta.requiresAuth)) {
          // if route requires auth and user isn't authenticated
          if (!store.state.Authentication.authenticated) {
            let query = to.fullPath.match(/^\/$/) ? {} : { redirect: to.fullPath }
            next(
              {
                path: '/login',
                query: query
              }
            )
            return
          }
        }
        next()
      }
    )
    

    它允许我使用我的路由定义来处理身份验证和访客放置。

    {
      path: '/',
      component: load('Template'),
      children: [
        { path: '', component: load('Dashboard'), name: 'Dashboard' }
      ],
      meta: { requiresAuth: true }
    },
    {
      path: '/login',
      component: load('Authentication/Login'),
      name: 'login'
    },
    

    通过在 Vue 初始化组件之前调用它在路由器中,这将停止处理任何组件级事件。

    【讨论】:

      猜你喜欢
      • 2018-07-18
      • 2018-02-22
      • 2014-04-14
      • 1970-01-01
      • 2014-03-31
      • 1970-01-01
      • 2017-04-17
      • 1970-01-01
      • 2021-02-20
      相关资源
      最近更新 更多