Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.JS - how to use localstorage with Vue.JS

I am working on Markdown editor with Vue.JS, and I tried to use localStorage with it to save data but I don't know how to save new value to data variables in Vue.JS whenever the user types!

like image 933
mohamed youssouf Avatar asked Jan 02 '17 11:01

mohamed youssouf


People also ask

How do I use local storage on Vue?

vue . Local storage uses the setItem() method to save data as key-value pairs, the data must be a string so we convert the JSON into a string in order to save it from using JSON. stringify() method.

Can Vue run locally?

Running the app locallyThe Vue CLI comes with a built-in development server. This allows you to run your app locally so you can test it easily without needing to configure a server yourself. The CLI adds a serve command to the project's package.

Can I use localStorage in JavaScript?

The localStorage mechanism provides a type of web storage object that lets you store and retrieve data in the browser. You can store and access data without expiration; the data will be available even after a visitor closes your site. You'll normally access localStorage using JavaScript.


1 Answers

Note this was an edit in my question, but I make it separately answer as @nathanvda suggested.


I found the solution that I was looking for. first use watch method to detect changes on variable you are storing data on like this:

watch: {   input: function () {     if (isLocalStorage() /* function to detect if localstorage is supported*/) {       localStorage.setItem('storedData', this.input)     }   } } 

This will update variable’s value whenever user add new inputs.

Then assign the new value to variable like this:

app.input = localStorage.getItem('storedData'); 

And that's it :)

like image 117
mohamed youssouf Avatar answered Sep 23 '22 02:09

mohamed youssouf