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

Ensure that the promise is fulfilled only if a specific condition is met

I have a complex if-else condition in my code that includes different promises. Once the logic determines which condition to enter and executes the corresponding promise, I need to ensure that a final promise is always executed. if (a < 5) { vm.pr ...

Encountering an Issue while Deploying a create-react-app to Heroku

Despite trying various online remedies, I am still encountering an error while attempting to deploy a simple React.js app on Heroku. The app successfully builds when I execute git push heroku master, but upon opening it, I consistently receive an applicati ...

AJAX-powered Form Validation

I am in the process of creating a login form that includes three input fields: one for entering a username, another for entering a password, and a submit button to log in. Currently, I am utilizing AJAX to validate the login information directly on the cl ...

Is having async as false really detrimental?

Splitting my inquiry into two sections. Within my website, I am dynamically generating some divs by utilizing ajax post requests to retrieve data from the database. Following is the structure of my setup. <html> <body> <script type=" ...

Is there a way to simultaneously send a file and additional information in Flask?

Below is the code I am using to upload a file to Flask. Client Side: <form id="upload-file" method="post" enctype="multipart/form-data"> <fieldset> <label for="file">Select a file</label> <input name="file8" ...

Is there a glitch in the Selenium Java CSS Selector functionality?

Everything seems to be working smoothly with that code! It successfully locates and clicks on my button within the span tag. driver.findElement(By.cssSelector("span[id$=somePagesCollection] a")).click(); However, after clicking the button, an input field ...

Node JS: Despite modifying the URL, the response remains unchanged

My attempt to log in to teeSpring.com and retrieve a response from another URL using a login cookie seems to be causing an issue. Upon logging into teeSpring.com, the dashboard details are returned. However, when I try to make a GET request to the second U ...

Can side effects be safely incorporated within the callback of the useState hook?

Consider this scenario: const [value, setValue] = useState(false); const setSomething = (val) => { setValue((prev) => { fn(); dispatch(action); // or any other side effect return prev + val; }); }; Is it acceptable and in line with ...

Modify URL parameters using history.pushState()

Utilizing history.pushState, I am adding several parameters to the current page URL after performing an AJAX request. Now, based on user interaction on the same page, I need to update the URL once again with either the same set of parameters or additional ...

Preserve the wpColorPicker selection using personalized knockout bindings

Utilizing wpColorPicker and knockout, my goal is to update the color picker value in my observable and then store it in the database as JSON. While other elements successfully update and save, there seems to be an issue with my custom binding for the data ...

Set the text for the "Select All Items" option in the PrimeVue Multiselect component to be customized

With PrimeVue, you have the option to include a header in the Multiselect component. This header appears above the checkbox used to select all items. To customize the appearance of the header, you can use the following CSS solution: div.customClassName .p ...

What is the best way to implement CSS in this JavaScript Fetch code in order to manipulate the text's position and font style

Hello, I am just starting out with JS. Is there a way for me to customize the position and font of text in this JS Fetch function using CSS? Any help will be greatly appreciated. let file = 'art.txt'; const handleFetch = () => { fe ...

The userscript is designed to function exclusively on pages originating from the backend, rather than on the frontend in a single-page application

I have a userscript that I use with Greasemonkey/Tampermonkey. It's set to run on facebook.com, where some pages are served from the backend during bootstrapping and others are loaded on the fly in the front-end using HRO, similar to how a Single Pag ...

unable to show image retrieved from JSON data

Looking to showcase the data from my JSON objects, which are displayed in 2 images below https://i.stack.imgur.com/yhqFy.png https://i.stack.imgur.com/DUgFO.png In the data, I have properties like c_name, max_slots, and an array slots. Within the array, ...

The video continues playing even after closing the modal box

I am facing an issue with my code where a video continues to play in the background even after I close the modal. Here is the code snippet: <div class="modal fade" id="videoModal" tabindex="-1" role="dialog" aria- ...

Utilizing Conditional Logic to Create a Dynamic Menu

I have a navigation menu on my website that is divided into two sections. There is a left panel and a right panel which slide in from the side when their respective buttons are clicked, covering the browser window. The functionality of sliding in the pan ...

Issue with content overlapping when hamburger icon is tapped on mobile device

When the hamburger menu is pressed on smaller screens, I want my navbar to cover the entire screen. To achieve this, I included the .push class in my code (see the jQuery and CSS) to trigger when the .navbar-toggle-icon is pushed. However, after implemen ...

Vanilla JS method for resetting Bootstrap 5 client-side validation when focused

I'm currently exploring Bootstrap 5's client-side validation feature. However, I've encountered a usability issue with the is-invalid class. After clicking the submit button, this class persists until the correct input is entered. I would li ...

Looping through color transitions upon hover using CSS

I am trying to create a color transition effect on hover, where the background changes from yellow to red and then back to yellow in a loop. I'm having trouble figuring out how to make this transition repeat continuously. Do I need to incorporate Java ...

Guide to resolving domain names in express.js

I've been working on an expressJS script that includes a mongoDB fetch. My objective is to create an API that displays my JSON-based test list on the /api/testlist route. When I try to access the index page, everything seems to be working fine. Howev ...