Vue Js Store Object in session Storage:To “Store” object in Vue.js is a centralized data store that allows components to share data and state. Session storage is a web storage API that allows data to be stored in the user’s browser session.
To store a Vue.js Store object in session storage, you can use the “JSON.stringify” method to convert the object into a string and then use the “sessionStorage.setItem” method to store the string in the browser’s session storage.
How can I store a Vue js store object in session storage ?
This is an example of how to store a JavaScript object in session storage using Vue.js:
First, create a new object with the user input and convert it into a JSON string using JSON.stringify()
.
Next, use the sessionStorage.setItem()
method to store the JSON string in session storage. You can use a unique key for each object to distinguish between them.
Then, add the saved object to the list of saved objects in Vue.js data.
Finally, clear the user input and display a toast message to confirm that the object has been saved.
Vue Js Store object in session storage Example
<div id="app">
<div>
<label>Name:</label>
<input type="text" v-model="name">
</div>
<div>
<label>Age:</label>
<input type="number" v-model="age">
</div>
<div>
<label>Email:</label>
<input type="email" v-model="email">
</div>
<button @click="saveObject">Save Object</button>
<div id="toast" class="toast">Data saved successfully!</div>
</div>
<script type="module">
const app = new Vue({
el: "#app",
data: {
name: '',
age: null,
email: '',
savedObjects: []
},
methods: {
saveObject: function () {
// Create a new object with the user input
var myObject = {
name: this.name,
age: this.age,
email: this.email
};
// Convert the object into a JSON string
var jsonString = JSON.stringify(myObject);
// Store the JSON string in the session storage
var index = sessionStorage.length + 1;
sessionStorage.setItem('myObject' + index, jsonString);
// Add the saved object to the list of saved objects
this.savedObjects.push(myObject);
// Clear the user input
this.name = '';
this.age = null;
this.email = '';
// Display the toast message
var toast = document.getElementById("toast");
toast.style.display = "block";
setTimeout(function () {
toast.style.display = "none";
}, 5000);
}
}
})
</script>