Search code examples
vue.jsvuejs2vuexvue-routerstore

Vue-router doesn't redirect to page after checking if value exists


Good day. I am trying to create a guard to my Vue application that only redirects to a page if a value in a state exists (not null or undefined). However when I use beforeEnter I get a circular reference and it doesn't redirect me to the page. If I use beforeRouteEnter I am redirected normally but if I updated the page I am not redirect to the previous page. What exactly is wrong here method can redirect me to the page after checking a store state?

The method in the store is very simple and I simply save whatever comes from the api call in my state, which starts out as null. What exactly is wrong here?

import Vue from 'vue'
import VueRouter from 'vue-router'
import form'@/components/form.vue'
import values'@/components/values.vue'
import store from '@/store.js'


Vue.use(VueRouter)
const routes = [
    { 
        path: '/', 
        component: form
    },
    { 
        path: '/values', 
        component: values,
        beforeRouteEnter (to, from, next) {
            guard(to, from, next)
        },
    }
]
const router = new VueRouter({
    mode: 'history',
    routes
})

const guard = function(to, from, next){
    let info = store.getters.result
    if(info){
        next('/values')
    } else {
        next('/')
    }
}

export default router

Solution

  • You have to use beforeEnter because beforeRouteEnter is the name of the in-component hook and will not work there. The reason you got a circular reference is that next('/values') redirects to itself. Change it to next() to tell the router to carry on with the current route with no redirect:

    const guard = function(to, from, next){
        let info = store.getters.result
        if(info){
            next()
        } else {
            next('/')
        }
    }