How to clear localStorage in VueJS?

Hi Friends 👋,

Welcome To SortoutCode! ❤️

To clear localStorage in Vue. We are going to use the localStorage.clear() method to remove all the object items from localStorage.

Today I am going to show you How you remove data in localStorage in VueJS?

Table of contains

  • Setup the Vue.js
  • Create FirstComponent.vue and import it into App.js
  • What is localStorage?
  • Short solution
  • Short Example

Let’s start today’s tutorial How do I remove data in localStorage in VueJS?

Setup the Vue.js

First, we have to install the Vue project, I had installed the vueJS in my system. If you haven’t installed or have any problem with installation you can follow this article, it will show you step by step process of installation.

How to Install the VueJS project?

Create FirstComponent.vue and import it into App.js

Create the new component in the src/components/ components folder. The component name is FirstComponent.vue and imported into the App.js file:

App.js

<template>
  <div id="app">
    <FirstComponent />
  </div>
</template>

<script>
import FirstComponent from "./components/FirstComponent.vue";
export default {
  name: "App",
  components: {
    FirstComponent,
  },
};
</script>

What is localStorage?

LocalStorage is the data storage type of web storage. This allows the Javascript sites and apps to store and access the data without any expiration date. It will not expire even after the browser close.

Short solution

To clear localStorage object items, we are going to use the clear() method to remove localStorage.clear() method. Let’s see the code syntax:

//clear localStorage object items
localStorage.clear(); 

Short Example

Let’s understand with an example. We are going to clear the localStorage object item.

FirstComponent.vue

<template>
  <div>
    <h1>clear the data from localStorage</h1>
  </div>
</template>
<script>
export default {
  name: "FirstComponent",
  data() {
    return {
      Days: ["sunday", "monday"],
      Month: ["Jan", "Feb"],
    };
  },
  mounted() {
    this.addData();
    setTimeout(() => {
      this.clearData();
    }, 5000);
  },
  methods: {
    addData() {
      localStorage.setItem("website", "sortoutcode");
      localStorage.setItem("days", JSON.stringify(this.Days));
      localStorage.setItem("months", JSON.stringify(this.Month));
      this.name = localStorage.getItem("website");
    },
    clearData() {
      localStorage.clear();
    },
  },
};
</script>

For now, let’s check the output.

Output

clear localStorage in VueJS

All the best 👍.

Follow me on Twitter