Vue.js Local Storage


Vue.js Local Storage– We can use the native javascript localstorage in Vue.js.JavaScript localStorage property allows us to save data in localstorage. Here in this tutorial, we are going to explain how you can use localstorage property to save data on client side. You can also use our online editor to edit and run the code online.


Vue.js Local Storage Example

Let us understand how localStorage works in JavaScript and how we can use it in vuejs. –

Syntax

Here is syntax of storage object-

var currStorage = window.localStorage;

This is used to access the current origin’s local storage space.

Set Item

You can set Item data in local storage simply as below-

localStorage.setItem('myItem', "Hello World!")

Get Item

You can read data from local storage simply as below-

var myData = localStorage.getItem('myItem');

Remove Item From LocalStorage

You can remove data from local storage simply as below-

localStorage.removeItem('myItem');

localStorage has no expiration time.

For Web Storage Api Details You can get more details here – Web Storage API Documentaion

Now let us create an example in vue.js.

Example:

<div id="app">	
  <p>Local Data = {{myLocalData}}</p>
	<button @click="mySetFunction()">Set Local Storage Data</button><br><br>
  <button @click="myGetFunction()">Get Local Storage Data</button><br><br>
   <button @click="myDeleteFunction()">Remove Local Storage Data</button>
  <p>Once Value is set in local storage Reload this page to see locally stored value.</p>
</div>
<script>
 new Vue({
el: '#app',
  
  data: { 
	  myStr:'Welcome to Tutorialsplane.com!',
    myLocalData: localStorage.getItem('myItem')
  },
  
   methods:{
    mySetFunction: function () {	
		localStorage.setItem('myItem', this.myStr);
    },
    myGetFunction: function () {	
		this.myLocalData = localStorage.getItem('myItem');
    },
     myDeleteFunction: function () {	
		 localStorage.removeItem('myItem');
     this.myLocalData = localStorage.getItem('myItem');
       
    }
   }

});
</script>

Try it »

Output of above example-

Vue.js Local Storage - JavaScript Example

Add Comment

Advertisements