I have successfully added custom global variables into Vue by injecting them. Here is the code snippet:
export default function (props, inject) {
inject('models', {
register(name) {
const model = require(`@/models/${name}.js`)
model.default(props, inject)
}
})
}
While this method works smoothly for me, I encountered a challenge when integrating these variables into the Vuex store in Nuxt.js. Although the store structure in Nuxt.js differs slightly from Vue.js, it operates in a similar manner.
Inside my store folder, the products.js file has the following contents:
export const state = () => ({
products: [],
})
export const getters = {
get_product: state => async id => {
let loadedProduct = state.products.find(p => p.id == id)
let isAlreadyLoaded = loadedProduct != null ? loadedProduct : false
if(isAlreadyLoaded)
{
return loadedProduct
}
else
{
let fetchedProduct = await this.$products.find(id)
return fetchedProduct
}
}
}
In this setup, the aim is to check whether we already have the product cached. If so, we return the cached product; otherwise, we fetch it. However, an error occurs when trying to access this.$products:
TypeError: Cannot read properties of undefined (reading '$products').
When accessing the store, my approach involves the following code:
async asyncData({store, params, $products}) {
let product = await store.getters['products/get_product'](params.id)
return {
product
}
},
To resolve this issue, I attempted using Vue.prototype.$products instead of this.$products within the Vuex store, but unfortunately, it did not provide a solution. Are there any suggestions on how to utilize a global variable within the Vuex store effectively?