Ben Carey
Ben Carey

Reputation: 16968

Set default meta properties on Vue Router

I have searched the documentation here, and whilst there is a meta property on the VueRouter object, it doesn't seem to be doing anything (there is no description on the actual property in the docuementation)...

Consider the following routes:

let routes = [
    {
        path: '/',
        component: require('./views/Home').default
    },
    {
        path: '/about',
        component: require('./views/About').default,
        meta: {
            transitionColor: '#000' // Note this property
        }
    }
];

I would like to do something like this:

export default new VueRouter({
    mode: 'history',
    routes,
    meta: {
        transitionColor: '#fff'
    }
});

The intention of the above code is to set the default $route.meta.transitionColor to #fff for all routes, and then allow the route to override this if it is supplied in the route level meta.

Is there a way to set default meta properties on Vue Router in this way?

Upvotes: 4

Views: 1246

Answers (2)

Mayinx
Mayinx

Reputation: 374

NavGuards are pretty handy - here's an simple example how to achieve something like you requested but using another meta-property - here called in router/index.ts somewhere after createRouter was invoked. The example declares every page without an explicitly auth-declaration as private using the custom meta-property requiresAuth (and sets the page title afterwards, while we're on it):

router.beforeEach((to, from) => {
  if (!Object.prototype.hasOwnProperty.call(to?.meta, "requiresAuth")) {
    to.meta.requiresAuth = true;
  }
  document.title =
    "APP BRAND - " + i18n.global.t(`component.appNav.${String(to.name)}`);
  next();
}); 

Upvotes: 0

Lueton
Lueton

Reputation: 171

To my knowledge, it does not exist. However, with navigation guards, you can achieve something very similar.

router.beforeEach((to, from, next) => {
   // manipulate route (e.g. set meta)
});

Upvotes: 3

Related Questions