Home > front end >  Using global variables inside Vuex store
Using global variables inside Vuex store

Time:10-21

I injected custom global variables into vue. You can see the code below.

export default function (props, inject) {
    inject('models', {
        register(name) {
            const model = require(`@/models/${name}.js`)
            model.default(props, inject)
        }
    })
}

this works and i don't have problems using this, the only problem is when loading them into vuex store. I'm using Nuxt.js where the store is a little bit diffrent then vue.js, but it almost works the same. my products.js in the store folder looks like this:

export const state = () => ({
    products: [],
})

export const getters = {
    get_product: state => async id => {
        let loadedProduct = state.products.find(p => p.id == id)
        let isAllreadyLoaded = loadedProduct != null ? loadedProduct : false
        if(isAllreadyLoaded) 
        {
            return loadedProduct
        }
        else 
        {
            let fetchedProduct = await this.$products.find(id)
            return fetchedProduct
        }
    }
}

I simply check first if i allready have the product in cache, if it is, I want to return that product, otherwise i want to fetch a product. But, i'm getting an error on this.$products. The error said:

TypeError: Cannot read properties of undefined (reading '$products'). 

and this is how i'm accessing my store:

async asyncData({store, params, $products}) {
        let product = await store.getters['products/get_product'](params.id)
        return { 
            product
        }
},

I allready tried to use Vue.prototype.$products instead of this.$products in vuex store, but unfortunatly this did not help. Any solutions? I need to use a global variable inside the vuex store

CodePudding user response:

In Nuxt it works different, you have to make a plugin and then inject it there.

See: https://nuxtjs.org/docs/directory-structure/plugins/#inject-in-root--context

CodePudding user response:

In the mean time, I did tried somethings myself. What I found is maybe something that could help others with the same problem.

In the vuex store you cannot access custom global injected variables, but you can access the main window variable. What i found out, was that there is a $nuxtjs property inserted into window, so you can access global nuxt variables by using:

let mycustomvariable = "$products"
window.$nuxt[mycustomvariable]
  • Related