The shared global variable or store feature is currently not functioning as expected in Vue JS

Currently, I am in the process of developing a Simple Web application using Vue JS for educational purposes. Although I am new to Vue JS and still learning the ropes, I have encountered an issue with sharing a state variable across all components.

In my attempts to accomplish this, I referred to a helpful thread at this link. However, I discovered that the state cannot be modified from a different component as intended. The code snippet below outlines my current setup:

To begin, I created a file dedicated to the global store with the following definition:

<script>
    import Vue from 'vue';

    export const globalStore = new Vue({
        data: {
            numOfViewers: 0
        }
    })
</script>

Subsequently, I utilized the numOfViewers attribute from the globalStore in a specific component named Header:

<template>
  <header class="app-header navbar">
    <b-nav is-nav-bar class="ml-auto">
      <div class="watching">
        <span class="watching-num"><i class="fa fa-eye"></i> {{ numOfViewers }}</span>
        <span class="watching-label">Watching now</span>
      </div>
    </b-nav>
  </header>
</template>
<script>
  import { globalStore } from '../GlobalStore';
export default {
  name: 'header',
    data(){
      return {
        numOfViewers : globalStore.numOfViewers
      }
    },
    //other code
}
</script>

Moreover, I attempted to update this value in the Header component from another component by taking the following steps:

Initially, I imported the globalStore into the Dashboard component:

import { globalStore } from '../GlobalStore';

Then, within the mounted() event of the component, I tried to alter the value as shown below:

globalStore.numOfViewers = 100;

Unfortunately, despite these efforts, the data value in the Header component remained unaltered. How can I resolve this issue and ensure that the modifications are reflected correctly?

Answer №1

If you move the variable numOfViewers to the computed property, it may improve performance:

computed: {
  numOfViewers() { return globalStore.numOfViewers; }
}

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

Stop the execution of client-side code in a Nuxt SSR web application

After setting up a SSR/progressive nuxt project using create-nuxt-app, I encountered an issue with HTTP requests being made from my two pages to a backend API. These requests are initiated from the async asyncData(ctx) method in my nuxt page. Strangely, w ...

Leveraging Window Object in Custom Hooks with NextJS

ReferenceError: window is not defined This issue arises on the server side when NextJS attempts to render the page. However, it is possible to utilize window within the useEffect hook by following the guidance provided here. I am seeking advice on creati ...

Node/ejs not recognizing Javascript files

I have been working on implementing a JavaScript code to create a hamburger menu when the screen is at a specific size, but unfortunately, nothing seems to happen. Here is how my directory structure looks like: public imgs javascript menu. ...

Ensuring contact form accuracy using jQuery and PHP

Can't seem to figure out why I am always getting false from the PHP file even though my contact form validation with jQuery and PHP is working fine. Let me explain with my code: Here is the HTML: <form method='post'> <label& ...

Is there a method to track the progress of webpage loading?

I am working on a website built with static HTML pages. My goal is to implement a full-screen loading status complete with a progress bar that indicates the page's load progress, including all images and external assets. Once the page has fully loaded ...

Accessing a precise div element in a webpage

Currently, I am utilizing Vue.js and Nuxt for my web development. One issue I am facing is related to anchors. Specifically, when I navigate to mysite.com/page1#section1, I want the page to scroll to section1. In my code, I have the following snippet: < ...

Establishing a unique URL and updating Vue.js Vuex state based on its parameters

My Vue.js Single Page Application allows users to input multiple values to create a recipe, all stored in Vuex state. I want to generate a URL based on these values so that users can share the recipes they create via a link. I envision a "share" button th ...

Passing parameters to JavaScript onload event from PHP

Looking for help with integrating date data from PHP into a JavaScript countdown function. I have extracted the date from a database using PHP, but struggling to pass it correctly to the JavaScript function. My attempt so far: <body onload="countIt(< ...

Sending a JavaScript variable to a Flask url_for function

There is an endpoint that requires a value in the URL and then generates content to be displayed within a specific div. I'm trying to construct the URL using url_for with a JavaScript variable, but it seems that $variable1 is being treated as a string ...

Display or conceal <ul>'s using JavaScript when the mouse enters or leaves

I'm encountering an issue with a basic JavaScript function. The goal is to toggle the dropdown menu on my website when the mouse hovers over or leaves the menu. The problem arises because my script is triggered by the ul tags within my menu, and I ha ...

The Chrome Keyboard on Android seamlessly passes words to the next input field when the focus changes in JavaScript

When using two input fields, pressing the enter key on the first field in Chrome (49) on Android (6.0.1) carries over the last word typed to the new input due to the right-bottom button on the standard keyboard. Is there a way to prevent this behavior or a ...

Activate video in Slick Slider with the click of a button

I am facing an issue with my slider setup, where each slide contains a video as the background along with play/pause buttons. When I try to play the video by clicking the corresponding button on a specific slide, I encounter this problem: if I click the pl ...

Executing webpack with specific settings in Node.js

In my current package.json file, I have a script defined as follows: "build": "webpack --inline --colors --progress --display-error-details --display-cached", Additionally, there is a webpack.config.js file located at the root of my repository. To strea ...

Performing mathematical operations in JavaScript, rounding to the nearest .05 increment with precision up to two

Apologies in advance. After reviewing multiple posts, it seems like the solution involves using the toFixed() method, but I'm struggling to implement it. $('.addsurcharge').click(function() { $('span.depositamount&ap ...

I need help converting the "this week" button to a dropdown menu. Can someone assist me in troubleshooting what I am missing?

Seeking assistance with customizing the "this week" button on the free admin dashboard template provided by Bootstrap 4. Looking to turn it into a dropdown feature but unable to achieve success after two days of research and watching tutorials. See code sn ...

Having trouble with the "next" pagination button not loading cards, even though the numbered buttons are working perfectly

My pagination numbers are functioning correctly, but I'm having trouble with my "next" or "previous" buttons. I am using Bootstrap 5 and jQuery to load cards from an array. The issue seems to be with the currentPage variable in my displayList function ...

Preserve user-inputted text from jQuery within a div container

With the help of the knowledgeable individuals here, I successfully created a prototype to address an issue I had encountered. The problem involved using a textbox input with a password requirement to update an HTML element. Although everything is functio ...

The function of style.marginRight differs from that of style.marginLeft

One function aligns content to the left while the other doesn't align it to the right function openNavLeft() { document.getElementById("mySidenavLeft").style.width = "100vw"; document.getElementById("main").style.marginLeft = "100vw"; } function ...

What is the best way to redirect a URL to include www using Node.js?

What is the best way to redirect a URL to start with www? For instance: ---> ...

Silhouettes dancing across handcrafted designs

I have been trying to create a custom geometry using vertices and faces, but I am facing an issue where the geometry does not cast shadows on itself and the faces all have the same color as it rotates. I have attempted various solutions but haven't ha ...