HTML web storage has 2 options to store data and those are localStorage and sessionStorage. These two objects are part of window and lets us store data on client side. The main difference between these two are sessionStorage data will lost once the tab is closed. However the localStorage data will not be removed even after closing the browser. In this brief article we will se how to use store data on client side with vuejs localstorage.

The localStorage can store 5MB of data and can contain strings only. So for storing strings only, the storage limit is enough.

VueJS localStorage

Now lets talk about how to use it with VueJS. Lets create a VueJS project and add the following into the App.vue file.

<template>
  <input v-model="car" placeholder="Add a new car" /> <br /><br />
  <input type="submit" @click="storeCar" value="Store" />
  <button @click="getCars">Get List</button>

  <ul class="list">
    <li v-for="(car, i) in cars" :key="i">
      {{ car }}
    </li>
  </ul>
</template>

Here in the template we have one input, two buttons, and a list. So basically we have a list of cars that we will render here in the list.

The input and submit button will be used to store a new car into the list. The second button will be used to get all the cars from the client storage.

<script>
export default {
  name: "App",
  data() {
    return {
      cars: [],
      car: "",
    };
  },
  methods: {
    storeCar() {
      
    },

    getCars() {
      
    },
  },
};
</script>

Here we have two properties inside data. One is the list of cars and other one is to bind with our input.

Inside the methods of vuejs localStorage we have two methods. First one is to store a new car and next one is to pull all the cars from storage.

Lets start with the storeCar method.

storeCar() {
  if (this.car.length) {
    // push the new car to list
    this.cars.push(this.car);

    // store the data in localStorage
    localStorage.setItem("cars", JSON.stringify(this.cars));

    // clear the input
    this.car = "";
  }
},

First we are pushing the car into the cars list then we are storing the list into localStorage. setItem method is used to store data and as we have shared earlier, localStorage can store string only.

So we need to make sure we use JSON stringify before saving it.

At the last line we will reset the input to make it blank again.

getCars() {
  this.cars = JSON.parse(localStorage.getItem("cars"));
},

Inside the getCars method we just need a single line of code to pull the list from storage with vuejs localstorage.

Now try to insert your first car and then click on get cars. You will be able to see the cars list.

Refresh the browser and you will still be able to get the list. So this is the way to use store data in client side with vuejs localStorage.

Here is a quick example of what we have made in this article. Please follow this sandbox link to play with the demo.