Leveraging global variables within Vuex state management strategy

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?

Answer №2

During this period, I took it upon myself to experiment with some solutions. Interestingly enough, I stumbled upon a potential solution that could benefit others facing the same issue.

It appears that in the Vuex store, you are unable to access custom global injected variables directly. However, there is a workaround - you can tap into the main window variable instead. Upon further investigation, I discovered a $nuxtjs property embedded within the window object. This means you can retrieve global Nuxt variables by utilizing the following code snippet:

let myCustomVariable = "$products"
window.$nuxt[myCustomVariable]

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Obtaining cookies from a different frame in Vue.js: A guide

I'm using a Google sign-in button that opens a new window for authorization. Is it possible to retrieve cookies from that frame? If so, the next question is "how?" :) The image below displays my cookies (localhost) and the cookies received from Googl ...

Add a fresh record only if it contains information and there are no existing duplicates present

Is it possible to create a note with both a title and text, under certain conditions? The title must not be empty The title cannot already exist in the system When attempting to check for duplicates within my array, the boolean value always returns true ...

Generating Placeholder Variables Within a v-for Iteration

Encountering a problem with Vue-JS involving v-for loops and v-model properties. I have an array of items: <input v-for="i in list" v-model="i.model" ... (other tags that use i) > </input> Accompanied by some JavaScr ...

What causes vue.js to be unable to function within HTML documents?

I was trying to integrate Vue.js into my Spring Boot application. Even though the build seemed successful, I am encountering issues with getting the Vue component to work properly. Here is a code snippet of my simple component, MenuBar.vue: <template> ...

Running repetitive tasks in PHP using setInterval function

I've been working on adding a "friend request" feature to my website and I really want the requests to show up instantly without having to reload the page. After doing some research, it seems like using setInterval with Ajax is the way to go. I found ...

I find the SetInterval loop to be quite perplexing

HTML <div id="backspace" ng-click="deleteString(''); decrementCursor();"> JS <script> $scope.deleteString = function() { if($scope.cursorPosVal > 0){ //$scope.name = $scope.name - letter; ...

Each time new scripts are loaded, the Angular 13 window.ng.ɵcompilerFacade gets swapped out for a fresh

New Update: After observing the behavior of loading components/modules in my application, I have noticed a conflict arising between window.ng.ɵcompilerFacade and v13 compliance format when switching between Angular versions. The issue occurs when loading ...

Why does Froala Editor not maintain formatting when retrieving data from the database?

I've been using the Froala editor to add content on my website, and it's doing well for inserting data into the database. However, I'm facing an issue when retrieving data from the database as it doesn't maintain the original formatting ...

What is the best way to manage a vuex dispatch response?

Despite feeling like the answer is right in front of me, I'm waving the white flag and seeking suggestions. The challenge lies in my login form that submits to an AWS API and reacts to the result. The trouble starts when the handleSubmit method is tr ...

Having trouble with my loop using Jquery's $.get method

Having an issue with Jquery mobile / JavaScript I'm struggling to properly loop through the different values of data in my "get" function, where it should be sending ...cmd=PC&data=06464ff ...cmd=PC&data=16464ff ...cmd=PC&data=26464ff ...

What is the best way to extract the value associated with the "first_name" key in the given object?

What is the best way to extract the value associated with the first_name key from the object below? { "first_name": "D", "last_name": "N", "phone_number": 1233414234 } ...

The router.push function does not properly redirect to the specified path; instead, it just reloads the current page

I am a newcomer to NextJS and facing a challenge where I need to transfer data from the current page to another page. However, instead of loading the defined path in router.push as pathname: "/booking/checkout/", it loads the current page. I wan ...

Using three.js to establish an Image for Particle

I am looking to make some changes to this demo: Instead of having colored particles, I want to assign an image to each one. Should I use a cube for this purpose? Or is there a way to use an image with Vector3? Here is the code for the example: i ...

What steps need to be taken to utilize the fast-json package within a web browser environment?

In my quest to enhance the performance of my apps, I stumbled upon two intriguing packages. Currently, I am working on a forum-style app that constantly receives and processes information from APIs. Despite optimizing my frontend JavaScript to the best of ...

The resetFields() function fails to execute

While utilizing Vue3 with Element Plus to create a form, I encountered an issue with the resetFields() method not working as expected. The form is unable to automatically refresh itself. In the child component (Edit.vue): <template> <el-dialo ...

Managing DOM elements within a Vue 3 template using Typescript

As I delve into the world of Vue 3 as a beginner, I encountered a challenge when it came to managing the DOM within Vue 3 templates. Let's take a look at the source code. MainContainer.vue <template> <div class="main-container" r ...

ES6 does not allow the use of native setters when extending the HTMLButtonElement

Looking for a way to utilize the native setters and getters for an extended HTMLButtonElement, particularly focusing on the 'disabled' property. You can find more information about the property here: https://developer.mozilla.org/en-US/docs/Web/ ...

What is the best way to choose CSS class attributes using Mootools and the getStyle()

Seeking to duplicate an object, I am trying to figure out how to retrieve class CSS attributes from Mootools. css: .card { width: 109px; height: 145px; } html: <div id="cards"> <div class="card" id="c0"> <div class="face fron ...

Unable to append XML nodes using jQuery's parseXML function, but able to append font

Jquery : $.get("config.xml",function(xml){ $(xml).find("config").find("images").append("<image><url>../demo/Headline/2012/12/20/0/0/A/Content/8/Web201212_P8_medium.jpg</url><name></name><redirect>none</r ...

Using jQuery to create an array variable and Passing the array to a different PHP page

Although I have managed to create a function that works perfectly for me, I am facing an issue with the jQuery part at the bottom. Currently, I am only able to trigger an alert message and not store the data as a real variable. The function is functionin ...