In my development work with Nuxt.js, I am utilizing the cookie-universal-nuxt
package to access cookies in both server-side and client-side.
modules:[
[.....] ,
[.....] ,
[.....] ,
['cookie-universal-nuxt', { alias: 'myCookie' }],
]
I have a helper function set up as follows:
// helper.js
const func = {
getSomthingFromCookie(check){
return this.$myCookie.get('check') === check ? "something" : "else"
}
}
export default func
// other functions
const mixin = {
methods: {
getSomthingFromCookie(check){
return this.$myCookie.get('check') === check ? "something" : "else"
}
}
}
Vue.mixin(mixin)
// use this.getSomthingFromCookie outside
This function is then used in various places such as store.js or Page.vue:
// Page.vue or store.js
<div>{{ helper.getSomthingFromCookie("test") }}</div>
..
..
..
..
..
import helper from '~/function/helper.js'
OR
const result = helper.getSomthingFromCookie("test")
However, when trying to run the function, an error occurs:
Cannot read property 'get' of undefined
The issue seems to be that the helper.js
file cannot access the Vue instance, specifically the this.$myCookie
.
I attempted to resolve this by importing Vue and logging it:
import Vue from 'vue'
console.log(Vue)
But the output in the terminal was not conclusive.
Considering alternate options, I thought about passing the cookie value into the function:
getSomthingFromCookie(check,cookie){
return cookie === check ? "something" : "else"
}
However, this approach would require extensive code modifications. Any suggestions or more efficient solutions would be greatly appreciated.