我的应用程序中有以下路线:
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;
我想访问公共模块中的元字段。怎么可能?
可以通过 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;
适用于 vue3 组合 api
import { useRoute} from 'vue-router'
const route= useRoute()
const pageType = route.meta.pageType