Vue.JS - 如何将localstorage与Vue.JS一起使用 [英] Vue.JS - how to use localstorage with Vue.JS

查看:210
本文介绍了Vue.JS - 如何将localstorage与Vue.JS一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Vue.JS编写Markdown编辑器,我尝试使用localstorage来保存数据但我不知道每当用户输入时如何在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!

推荐答案

注意这是我的问题中的一个编辑,但我将其单独回答为@nathanvda建议。

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

我找到了我正在寻找的解决方案。首先使用watch方法来检测存储数据的变量的变化,如下所示:

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');

就是这样:)

这篇关于Vue.JS - 如何将localstorage与Vue.JS一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆