使用Vuex将Vue数据存储到localStorage
When talking about storing data, there are various ways to persist data.在谈论存储数据时,有多种保留数据的方法。One is very simple, it’s perfect for prototypes, and it’s storing the data using the Web Storage API: l...
When talking about storing data, there are various ways to persist data.
在谈论存储数据时,有多种保留数据的方法。
One is very simple, it’s perfect for prototypes, and it’s storing the data using the Web Storage API: localStorage and sessionStorage.
一种非常简单,非常适合原型,并且使用Web Storage API (本地存储和sessionStorage)存储数据。
Using Vue you can make use of that API in many ways. One of the simplest ones is to rely on the vuex-persist library.
使用Vue,您可以通过多种方式使用该API。 最简单的方法之一是依靠vuex-persist库。
You install it using npm or Yarn:
您使用npm或Yarn安装它:
npm install vuex-persist
#or
yarn add vuex-persist
Open the Vuex store file, and add:
打开Vuex存储文件,然后添加:
import VuexPersist from 'vuex-persist'
Initialize VuexPersist:
初始化VuexPersist:
const vuexPersist = new VuexPersist({
key: 'my-app',
storage: window.localStorage
})
key is the key that’s used in the localStorage database.
key是localStorage数据库中使用的密钥。
Change localStorage with sessionStorage to use that other storage system (each has its own peculiarities, see the Web Storage API document I linked above).
使用sessionStorage更改localStorage以使用其他存储系统(每个存储系统都有其自身的特性,请参见我上面链接的Web Storage API文档)。
Next up, add vuexPersist to the list of Vuex plugins, when initializing the store:
接下来,在初始化商店时,将vuexPersist添加到Vuex插件列表中:
const store = new Vuex.Store({
//...initialization
plugins: [vuexPersist.plugin]
})
That’s it! Any time the store is changed, the library will persist it to the browser.
而已! 每次更改存储时,库都会将其持久保存到浏览器中。
There are more advanced capabilities you can find out on the official documentation, but these are the basics to get you started.
您可以在官方文档中找到更多高级功能,但这是入门的基础。
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐



所有评论(0)