將Vue的數據存儲到localStorage使用Vuex

學習如何自動將Vuex數據存儲到localStorage或sessionStorage中。 在談到數據存儲時,有各種不同的方法可以持久化數據。 其中一種非常簡單,非常適合原型,就是使用Web Storage API:localStorage和sessionStorage。 使用Vue,您可以以多種方式使用該API。其中最簡單的方法之一是依賴於vuex-persist庫。 您可以使用npm或Yarn安裝它: npm install vuex-persist #或者 yarn add vuex-persist 打開Vuex存儲文件,添加以下代碼: import VuexPersist from 'vuex-persist' 初始化VuexPersist: const vuexPersist = new VuexPersist({ key: 'my-app', storage: window.localStorage }) key是在localStorage數據庫中使用的鍵。 使用sessionStorage替換localStorage以使用其他存儲系統(每個存儲系統都有其自身的特點,請參閱上面我提供的Web Storage API文檔)。 接下來,在初始化store時,將vuexPersist添加到Vuex插件列表中: const store = new Vuex.Store({ //...初始化 plugins: [vuexPersist.plugin] }) 就這樣!每次更改store,該庫將把數據持久化到瀏覽器中。 您可以在官方文檔中找到更多高級功能,但這些是入門的基礎內容。