I recently implemented Nuxt JS's inject
feature to add a reusable function to my page. However, I'm facing challenges trying to utilize this function in another plugin file. Here's the setup:
- 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
})
}
Now, when trying to use the getAffiliate
function from my tracking.js file in another plugin file:
- plugins/init-brand.js
export default async function ({ app, route, store }) {
const affiliate = app.$getAffiliate()
console.log(affiliate) <-- shows undefined
}
I've attempted different methods such as:
app.$getAffiliate()
this.$getAffiliate()
<-- this works in a Vue file$getAffiliate()
this.getAffiliate()
What step am I missing to access the getAffiliate
function in another plugin file?