亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Vuex數(shù)據(jù)持久化實(shí)現(xiàn)的思路與代碼

 更新時間:2021年05月16日 09:44:23   作者:隨遇而安  
Vuex數(shù)據(jù)持久化可以很好的解決全局狀態(tài)管理,當(dāng)刷新后數(shù)據(jù)會消失,這是我們不愿意看到的。這篇文章主要給大家介紹了關(guān)于Vuex數(shù)據(jù)持久化實(shí)現(xiàn)的思路與代碼,需要的朋友可以參考下

什么是vuex

vuex :是一個專為vue.js開發(fā)的狀態(tài)管理器,采用集中式存儲的所有組件狀態(tài)

五個屬性: state、getters、mutations、actions、module

基本使用:

新建store.js文件,最后在main.js中引入,并掛載到實(shí)列上

   import Vue from 'vue'
   import Vuex from 'vuex'
   Vue.use(Vuex)
   const state = {}
   const getters = {}
   const mutations = {}
   const actions = {}
   export default new Vuex.Store({
       state,
       getters,
       mutations,
       actions
   
   })

state屬性: 存放狀態(tài),例如你要存放的數(shù)據(jù)

getters: 類似于共享屬性,可以通過this.$store.getters來獲取存放在state里面的數(shù)據(jù)

mutations: 唯一能改變state的狀態(tài)就是通過提交mutations來改變,this.$store.commit()

actions: 一步的mutations,可以通過dispatch來分發(fā)從而改變state

Vuex 數(shù)據(jù)持久化

眾所周知,Vuex 的數(shù)據(jù)是存儲在內(nèi)存中的,刷新一下網(wǎng)頁這些數(shù)據(jù)就會丟失。而有些數(shù)據(jù)我們希望刷新后仍然能夠留存,這就需要把數(shù)據(jù)存儲下來。這里就記錄一下,使用 localStorage 來持久化 Vuex 中的數(shù)據(jù)。

實(shí)現(xiàn)思路

  • 因?yàn)?state 中的數(shù)據(jù)理論上只能通過 mutation 來進(jìn)行更新,所以可以監(jiān)聽 mutation 事件,在每次事件執(zhí)行后,將此時整個 state 的數(shù)據(jù)轉(zhuǎn)為字符串后存儲進(jìn) localStorage。
  • 在頁面初始化 state 時,讀取 localStorage 值,重新轉(zhuǎn)為 JSON 后,合并進(jìn)當(dāng)前 state。
  • 這種方法只是一個簡單的實(shí)現(xiàn),只適用于簡單對象,對復(fù)雜對象來說,重新轉(zhuǎn)為 JSON 可能會失去對應(yīng)的事件和方法,后面可以考慮以其他方式存儲。

代碼

插件:

export default (options = {}) => {
  const storage = options.storage || (window && window.localStorage);
  const key = options.key || "vuex";

  // 獲取state的值
  const getState = (key, storage) => {
    const value = storage.getItem(key);
    try {
      return typeof value !== "undefined" ? JSON.parse(value) : undefined;
    } catch (err) {
      console.warn(err);
    }
    return undefined;
  };

  // 設(shè)置state的值
  const setState = (key, state, storage) =>
    storage.setItem(key, JSON.stringify(state));

  return (store) => {
    // 初始化時獲取數(shù)據(jù),如果有的話,把原來的vuex的state替換掉
    const data = Object.assign(store.state, getState(key, storage));
    if (data) {
      store.replaceState(data);
    }

    // 訂閱 store 的 mutation。handler 會在每個 mutation 完成后調(diào)用,接收 mutation 和經(jīng)過 mutation 后的狀態(tài)作為參數(shù)
    store.subscribe((mutation, state) => {
      setState(key, state, storage);
    });
  };
};

調(diào)用方式:

import VuexPersist from "@/plugins/VuexPersist";

export default createStore({
  plugins: [VuexPersist()],
});

總結(jié)

到此這篇關(guān)于Vuex數(shù)據(jù)持久化實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)Vuex數(shù)據(jù)持久化內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論