Home » vue » Shared global variable/store is not working in the Vue JS

Shared global variable/store is not working in the Vue JS

Posted by: admin November 26, 2021 Leave a comment

Questions:

I am developing a Simple Web application for learning purpose using Vue js. I am new to Vue JS and just started learning Vue. What I am doing now, I am trying to share a state variable for all components as in this link, https://forum.vuejs.org/t/how-set-global-state-available-to-all-components/5947. But, the state cannot be modified form the different component. This is my code.

I created a file for the global store with this definition

<script>
    import Vue from 'vue';

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

I am using the numOfViwers of globalStore in a component called Header like this

<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>

Then I am trying to modify that value in the Header component from another component like this.

I imported the globalStore in the Dashboard component like this

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

in the mounted() event of the component, I modify the value like this

globalStore.numOfViewers = 100;

But the data value in the Header component is not modified. How can I get it working?

Answers:

Moving numOfViewers to computed should help:

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