我正在使用Nuxt JS的inject
函数将一个函数注入到我的页面中,以提高代码的可重用性。我想在另一个插件文件中使用该函数,但似乎无法在其中获取该函数。
这是我的设置:
- plugins/utils/tracking.js
function setCookiePrefix () {
return 'fudge__'
}
function getCookie (app, name) {
try {
const prefix = setCookiePrefix()
const cookie = app.$cookies.get(`${prefix}${name}`)
if (!cookie || cookie == '') {
throw 'cookie not set'
}
return cookie
} catch (err) { }
return null
}
export default function ({ app, store, context }, inject) {
/*
* Get just the affiliate (cpm_id OR affiliate)
* examples: "my_brand", "blah"
*/
inject('getAffiliate', () => {
const affiliate = getCookie(app, 'affiliate')
const brand = getBrand(store)
if (!affiliate) return brand
return affiliate
})
}
我试图使用tracking.js文件中的getAffiliate
函数的文件:
- plugins/init brand.js
export default async function ({ app, route, store }) {
const affiliate = app.$getAffiliate()
console.log(affiliate) <-- undefined
}
我试过:
app.$getAffiliate()
this.$getAffiliate()
<--这在Vue文件中有效$getAffiliate()
this.getAffiliate()
访问另一个插件文件中的getAffiliate
函数缺少什么?
我有一个设置了一些axios的api插件。我可以将它加载到另一个插件文件中,如下所示:
export default ( {$api} , inject) => {
const service = new SomeService($api)
inject('someService', SomeService)
}
所以在你的情况下,这将是:
export default async function ({ app, route, store, $getAffiliate }) {
const affiliate = $getAffiliate()
console.log(affiliate)
}
不确定这是否是正确的方式,但它对我有效。