如何在 Vue 中停止组件加载和重定向?

Mar*_*cký 2 javascript vue.js vue-router vue-component

我有一个非登录用户无法访问的组件。我将这个逻辑实现到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>
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

Jus*_*hur 6

您应该将 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()
  }
)
Run Code Online (Sandbox Code Playgroud)

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

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

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