Vue3 -> How to watch for global variable changes.

Tony Mucci
Code Kings
Published in
2 min readJul 1, 2024
https://unsplash.com/@tem_rysh

Introduction

Managing the global state in Vue 3 is essential for creating responsive and scalable applications. One effective way to handle global variables is by using VueUse’s useStorage as your store, this method simplifies managing and watching for changes across your application.

The Problem

Handling global state can be challenging, especially when you need to persist data across sessions and ensure that changes are reactive and accessible throughout your application. Without a streamlined approach, you might end up writing repetitive code and facing issues with state synchronization.

The Solution

Setting Up the Store

VueUse’s useStorage allows you to create a reactive store that persists data in localStorage. Here’s how to set it up:

import { useStorage } from '@vueuse/core';

const store = useStorage('app-store', {
username: null,
// Add other properties as needed
});

Attaching the Store to Global Properties

To make the store accessible across all components, attach it to Vue’s global properties:

import { createApp } from 'vue';
import App from './App.vue';

const app = createApp(App);

app.config.globalProperties.$storage = store;

app.mount('#app');

Watching for Changes

In the component where you need to react to global state changes, set up a watcher:

export default {
name: 'YourComponent',
watch: {
'$storage.value.username': {
handler(nv, ov) {
console.log('New value:', nv);
console.log('Old value:', ov);
},
deep: true
}
}
};

This approach ensures your application remains reactive and state changes are handled efficiently, providing a clean and scalable solution to global state management in Vue 3.

Happy Coding!

--

--

Tony Mucci
Code Kings

Co-founder of SimpliCourt, dree, My Company Tools, and Eklect Enterprises