Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 598
Mukund Kumar Avatar asked Oct 16 '17 18:10

Mukund Kumar


1 Answers

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;
like image 145
thanksd Avatar answered Nov 05 '22 10:11

thanksd