Search code examples
vue.jsvue-router

How to access current route meta fields in common javascript module - VueJs


I have following route in my application:

const router = new Router({
  mode: 'history',
  scrollBehavior: () => ({ y: 0 }),
  routes: [
    { path: '/', component: HomePage, meta: { pageType: 'home'} },
  ],
});

and have on common js module:

const trackEvent = {
  getFields: () => {
  //here need to access meta fields(pageType) of current route. how is it possible ?
  }
}
export default trackEvent;

i want to access meta field in common module. how is it possible ?


Solution

  • The meta property is accessible via this.$route.meta on a Vue instance. Just pass that to the getFields method.

    export default {
      created() {
        let meta = getFields(this.$route.meta);
      }
    }
    
    getFields: (meta) => {
      console.log(meta);
    
      return meta.fields.pageType; // not sure what you're trying to return exactly
    }
    

    If you can't pass in the current route, you'll need to import the router object and get the current route from that:

    import router from 'path/to/your/router'
    
    const trackEvent = {
      getFields: () => {
        let meta = router.currentRoute.meta;
        console.log(meta);
    
        return meta.fields.pageType; // not sure what you're trying to return exactly
      }
    }
    export default trackEvent;