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

2

16

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 ?

Mcfarland answered 16/10, 2017 at 18:2 Comment(0)
C
27

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;
Cepheus answered 16/10, 2017 at 18:7 Comment(2)
i have some use case where i direct need to access meta field in JS Module without passing meta field from component.Mcfarland
Okay, you'll need to import the router object in that case. See my edit.Cepheus
S
0

For vue3 composition api

import { useRoute} from 'vue-router'

const route= useRoute()
const pageType = route.meta.pageType
Salerno answered 12/6 at 10:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.