Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

beforeEnter in Vue routes does not work for children routes

I am using vue 2.6.10 and in my vue's router.js I set some routes like so

Vue.use(Router)

const router =  new Router({
  mode: "history",
  base: process.env.BASE_URL,
  routes: [
    {
      path: '/login',
      name: 'login',
      component: Login,
    },    

    {
      path: '/shoes',
      name: 'shoes',
      component: Shoes,
      beforeEnter: (to, from, next) => { 
        if (store.state.login.quad_token == null) {
          next('/login');
        }
        next();
      },
      children:[
            {
              path: ':skateshoes',
              name: 'skateshoes',
              component: SkateShoes
            }, 
      //more children routes

The issue is that if I manually remove the cookie from my browser and got to /shoes/skateshoes I dont get redirected to the login page.

To get redirected, I have to edit the skateshoes children route like so

        {
          path: ':skateshoes',
          name: 'skateshoes',
          component: SkateShoes,
          beforeEnter: (to, from, next) => { 
            if (store.state.login.quad_token == null) {
              next('/login');
            }
            next();
          }
        }, 

I thought that putting beforeEnter in the parent will also work for all the children. Apparently this does not work , at least for me.

How do I make it work? Thanks

like image 715
codebot Avatar asked Oct 14 '25 18:10

codebot


1 Answers

You should use beforeEach guard instead of beforeEnter.

beforeEnter is a per route guard, it doesn't apply for children.

You can use router's meta combine with beforeEach to add conditional logic.

like image 184
ittus Avatar answered Oct 17 '25 10:10

ittus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!