Search code examples
vuejs3vue-router

How can I access router props passed in to Vue Router in function beforeEach


I have a Vue Router routes setup like so:

[
  {
    path: '/regions',
    name: 'regions',
    component: () => import(/* webpackChunkName: "regions" */ '../views/RegionsView.vue'),
    props: {
      endpoint: '/admin/regions/index'
    },
    meta: { 
      auth: true,
      role: ['admin'],
      permission: 'region-view'
    }
  }
]

I'm trying to access props from the route in the beforeEach() function, how can I do this?

router.beforeEach((
  to: RouteLocationNormalized,
  from: RouteLocationNormalized,
  next: NavigationGuardNext
) => {
  // console.log(to.props)???
  next()
})

Solution

  • You can use the meta key to pass data in routes.

    // route definition
    [
      {
        path: '/regions',
        name: 'regions',
        component: () => import(/* webpackChunkName: "regions" */ '../views/RegionsView.vue'),
        // props: {
        //   endpoint: '/admin/regions/index',
        // },
        meta: {
          auth: true,
          role: ['admin'],
          permission: 'region-view',
          props: {
            endpoint: '/admin/regions/index',
          },
        },
      },
    ];
    

    Then, it can be accessible in the beforeEach and other guards:

    // hook
    Router.beforeEach((from, to, next) => {
      console.log('from', from.meta.props?.endpoint);
      console.log('to', to.meta.props?.endpoint);
      next();
    });
    

    Based on the current router page, the props data would be in from or to or none.

    Finally, in the RegionsView component:

    // ../views/RegionsView.vue
    
    <script setup>
    import { useRoute } from 'vue-router';
    
    const route = useRoute();
    console.log('props', route.meta.props?.endpoint);
    
    </script>