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

2019-02-11 19:44发布

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!

3条回答
Anthone
2楼-- · 2019-02-11 20:33

you can use v-model to bind you variable with every change or you can put it computed :{} section.computed is like life hook of vue.js it re-render the component again when it values are changed.

查看更多
你好瞎i
3楼-- · 2019-02-11 20:39

You can just do following to save in localStorage

localStorage.setItem('YourItem', response.data)

You can fetch this using:

localStorage.getItem('YourItem')

To delete this from localStorage:

localStorage.removeItem('YourItem')
查看更多
smile是对你的礼貌
4楼-- · 2019-02-11 20:40

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 :)

查看更多
登录 后发表回答