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?