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

前端 未结 3 1369
梦谈多话
梦谈多话 2021-01-01 08:54

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 wheneve

3条回答
  •  [愿得一人]
    2021-01-01 09:30

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

提交回复
热议问题