We can use the vue-sessionstorage library to store Vue app data in session storage of our browser.
In this article, we’ll look at how to use it to save data.
Installation
We can install the library by running:
npm i vue-sessionstorage
Save Data in Local Storage
After installing the library, we can save data in local storage with by writing:
main.js
import Vue from "vue";
import App from "./App.vue";
import VueSessionStorage from "vue-sessionstorage";
Vue.use(VueSessionStorage);
Vue.config.productionTip = false;
new Vue({
render: (h) => h(App)
}).$mount("#app");
App.vue
<template>
<div id="app"></div>
</template>
<script>
export default {
name: "App",
mounted() {
this.$session.set("username", "user123");
}
};
</script>
We just register the plugin in main.js
.
Then we have the this.$session
object available for us to use anywhere.
We call set
with the key and value of the data we want to save to save it.
To get the data, we can use the this.$session.get
method:
<template>
<div id="app"></div>
</template>
<script>
export default {
name: "App",
mounted() {
this.$session.set("username", "user123");
console.log(this.$session.get("username"));
}
};
</script>
The this.$session.exists
method checks if a key exists:
<template>
<div id="app"></div>
</template>
<script>
export default {
name: "App",
mounted() {
this.$session.set("username", "user123");
console.log(this.$session.exists("username"));
}
};
</script>
The this.$session.remove
method removes the item with the given key:
<template>
<div id="app"></div>
</template>
<script>
export default {
name: "App",
mounted() {
this.$session.set("username", "user123");
console.log(this.$session.remove("username"));
}
};
</script>
The this.$session.clear
method clears session storage data with the given key:
<template>
<div id="app"></div>
</template>
<script>
export default {
name: "App",
mounted() {
this.$session.set("username", "user123");
console.log(this.$session.clear("username"));
}
};
</script>
With session storage, different instances of the same app can store different data in their own session.
The data can be set both per-origin and per-instance, which is per-window or per-tab.
So the clear
method will clear all data with the given key.
Conclusion
We can use the vue-sessionstorage library to save data to session storage.