最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to stop component-loading and redirect in Vue? - Stack Overflow

programmeradmin8浏览0评论

I have a ponent which is not to be accessed by non-logged-in user. I implemented this logic into the beforeCreate hook. Problem is that this doesn't stop the ponent from continuing in loading, which I want it to.

This is my code:

<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>

What am I doing wrong?

I have a ponent which is not to be accessed by non-logged-in user. I implemented this logic into the beforeCreate hook. Problem is that this doesn't stop the ponent from continuing in loading, which I want it to.

This is my code:

<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>

What am I doing wrong?

Share asked Sep 18, 2017 at 21:38 Martin HeraleckýMartin Heralecký 5,7893 gold badges31 silver badges67 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

You should move your beforeCreate function to the router itself. Here's my Auth catch

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()
  }
)

It allows me to use my routes definition to handle auth and guest placements.

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

By having it in the router it's called before the ponents are initialized by Vue, this will stop processing of any ponent level events.

发布评论

评论列表(0)

  1. 暂无评论