我使用Nuxt的inject函数将一个函数注入到我的页面中,以实现代码的可重用性。我想在另一个插件文件中使用这个函数,并且似乎无法在其中得到这个函数。
这是我的装备:
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
})
}我试图从我的getAffiliate文件中使用tracking.js函数的文件:
export default async function ({ app, route, store }) {
const affiliate = app.$getAffiliate()
console.log(affiliate) <-- undefined
}我试过:
app.$getAffiliate()this.$getAffiliate() <--这适用于Vue file$getAffiliate()this.getAffiliate()在另一个插件文件中访问我的getAffiliate函数缺少什么?
发布于 2022-02-10 12:26:03
我有一个api插件,并设置了一些axios。我可以将它装入另一个插件文件中,如下所示:
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)
}不知道这是不是正确的方法,但它对我有用。
https://stackoverflow.com/questions/70832664
复制相似问题