如何访问常见的javascript模块中的当前路由元字段 - VueJs

时间:2017-10-16 18:02:58

标签: vue.js vue-router

我的申请中有以下路线:

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

并拥有常见的js模块:

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

我想访问公共模块中的元字段。怎么可能?

1 个答案:

答案 0 :(得分:9)

可以通过Vue实例上的meta访问this.$route.meta属性。只需将其传递给getFields方法。

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
}

如果您无法传递当前路线,则需要导入router对象并从中获取当前路线:

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;