Open In App

How to Make localStorage Reactive in Vue.js ?

Last Updated : 12 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In Vue, localStorage is used to store data locally in the browser. However, by default, changes made to localStorage are not reactive in Vue. This means that if the localStorage is updated outside of the Vue component, the component will not be aware of the changes and will not update accordingly. This can lead to issues when trying to keep the component in sync with the localStorage data. In this article, we will see how to make the localStorage reactive in Vue.js, along with understanding the basic way to implement this concept.

Vue provides a way to make localStorage reactive by using Vue’s built-in reactive system. When we make a property reactive in Vue, any changes made to that property will trigger the re-rendering of the component. This makes it possible to keep the component in sync with the localStorage data.

Approach: To make localStorage reactive in Vue, we can use Vue’s reactive function to create a reactive object that will hold the localStorage data. Then, we can use the watch method to listen to changes in the reactive object and update the localStorage accordingly. The following is the approach we can follow:

  • Create a reactive object using Vue’s reactive function and initialize it with the localStorage data.
  • Watch the reactive object for changes using Vue’s watch method.
  • When the reactive object changes, update the localStorage with the new data.

Approach 1: In this approach, we have created a reactive object called “data” that holds the “message” property, which is initialized with the value from the localStorage. We are using the watch method to watch for changes in the “message” property and update the localStorage with the new value. The “message” property is also returned from the setup function so that it can be used in the template.

Example: This example illustrates the creation of the localStorage Reactive in Vue.js

HTML




<template>
    <div>
        <form @submit.prevent="addItem">
            <input v-model="newItem" 
                   placeholder="Enter item...">
            <button>Add Item</button>
        </form>
        <ul>
            <li v-for="(item, index) in items" 
                :key="index">
                {{ item }}
                <button @click="removeItem(index)">
                      Remove
                  </button>
            </li>
        </ul>
    </div>
</template>
  
<script>
    export default {
        data() {
            return {
                newItem: '',
                items: [],
            };
        },
        computed: {
            itemsFromLocalStorage() {
                return JSON.parse(localStorage.getItem('items') || '[]');
            },
        },
        watch: {
            items(newItems) {
                localStorage.setItem('items', JSON.stringify(newItems));
            },
        },
        methods: {
            addItem() {
                this.items.push(this.newItem);
                this.newItem = '';
            },
            removeItem(index) {
                this.items.splice(index, 1);
            },
        },
        created() {
            this.items = this.itemsFromLocalStorage;
        },
    };
</script>


Output:

 

Approach 2: In this approach, we’ve added a computed property totalItems which returns the total number of items in the items array. We also display this value in the template. When the component is mounted, we load the items array from localStorage using the mounted lifecycle hook. The addItem & removeItem methods are similar to the previous examples, adding and removing items from the items array respectively. However, we also update localStorage in these methods to persist the changes.

Example: This is another example that illustrates the creation of the localStorage Reactive in Vue.js

HTML




<template>
    <div>
        <form @submit.prevent="addItem">
            <input v-model="newItem" 
                   placeholder="Enter item...">
            <button>
                  Add Item
              </button>
        </form>
        <ul>
            <li v-for="(item, index) in items" 
                :key="index">
                {{ item }}
                <button @click="removeItem(index)">
                    Remove
                </button>
            </li>
        </ul>
        <p>
            Total Items: {{ totalItems }}
        </p>
    </div>
</template>
  
<script>
    export default {
        data() {
            return {
                newItem: '',
                items: [],
            };
        },
        computed: {
            totalItems() {
                return this.items.length;
            },
        },
        mounted() {
            
            // Load items from localStorage on component mount
            this.items = JSON.parse(localStorage.getItem('items')) || [];
        },
        methods: {
            addItem() {
                this.items.push(this.newItem);
                this.newItem = '';
                localStorage.setItem('items', JSON.stringify(this.items));
            },
            removeItem(index) {
                this.items.splice(index, 1);
                localStorage.setItem('items', JSON.stringify(this.items));
            },
        },
    };
</script>


Output:

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads