How to remove data from sessionStorage in VueJS?

Hi Friends 👋,

Welcome To SortoutCode! ❤️

To remove the data from sessionStorage in VueJS. We are going to use the sessionStorage.removeItem() to remove the data from sessionStorage.

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

Table of contains

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

Let’s start today’s tutorial How do I remove data in sessionStorage 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 sessionStorage?

SessionStorage is the data storage type of web storage. This allows the Javascript sites and apps to store and access the data. The data will be deleted when the browser closed.

Short solution

To remove the data from sessionStorage, we are going to use the removeItem() method to remove the data from sessionStorage. removeItem() method accepts the one parameter that is key. Let’s see the code syntax:

let name = 'sortoutcode';

//store the name data in sessionStorage
sessionStorage.setItem('website,name);    //sessionStorage.setItem(key);

// get data from sessionStorage
sessionStorage.removeItem('website);   // remove website key value

Short Example

Let’s understand with an example. First, we are going to remove the data from sessionStorage.

FirstComponent.vue

<template>
  <div>
    <h1>Data from sessionStorage</h1>
    <div>
      <p v-if="name">data: {{ name }}</p>
      <button @click="addData">Add Data</button><br />
      <button @click="removeData">Remove Data</button>
    </div>
  </div>
</template>
<script>
export default {
  name: "FirstComponent",
  data() {
    return {
      name: "",
    };
  },
  methods: {
    addData() {
      sessionStorage.setItem("website", "sortoutcode");
      this.name = sessionStorage.getItem("website");
    },
    removeData() {
      sessionStorage.removeItem("website");
      this.name = sessionStorage.getItem("website"); //key value is empty
    },
  },
};
</script>

For now, let’s check the output.

Output

remove data from sessionStorage in vuejs

All the best 👍.

Follow me on Twitter