老熟女激烈的高潮_日韩一级黄色录像_亚洲1区2区3区视频_精品少妇一区二区三区在线播放_国产欧美日产久久_午夜福利精品导航凹凸

重慶分公司,新征程啟航

為企業提供網站建設、域名注冊、服務器等服務

利用Dectorator分模塊存儲Vuex狀態的實現

1、引言

淮陽網站制作公司哪家好,找成都創新互聯公司!從網頁設計、網站建設、微信開發、APP開發、成都響應式網站建設等網站項目制作,到程序開發,運營維護。成都創新互聯公司于2013年創立到現在10年的時間,我們擁有了豐富的建站經驗和運維經驗,來保證我們的工作的順利進行。專注于網站建設就選成都創新互聯公司

在H5的Vue項目中,最為常見的當為單頁應用(SPA),利用Vue-Router控制組件的掛載與復用,這時使用Vuex可以方便的維護數據狀態而不必關心組件間的數據通信。但在Weex中,不同的頁面之間使用不同的執行環境,無法共享數據,此時多為通過BroadcastChannel或storage模塊來實現數據通信,本文主要使用修飾器(Decorator)來擴展Vuex的功能,實現分模塊存儲數據,并降低與業務代碼的耦合度。

2、Decorator

設計模式中有一種裝飾器模式,可以在運行時擴展對象的功能,而無需創建多個繼承對象。類似的,Decorator可以在編譯時擴展一個對象的功能,降低代碼耦合度的同時實現多繼承一樣的效果。

2.1、Decorator安裝

目前Decorator還只是一個提案,在生產環境中無法直接使用,可以用babel-plugin-transform-decorators-legacy來實現。使用npm管理依賴包的可以執行以下命令:

npm install babel-plugin-transform-decorators-legacy -D

然后在 .babelrc 中配置

{
  "plugins": [
    "transform-decorators-legacy"
  ]
}

或者在webpack.config.js中配置

{
  test: /\.js$/,
  loader: "babel-loader",
  options: [
    plugins: [
      require("babel-plugin-transform-decorators-legacy").default
    ]
  ]
}

這時可以在代碼里編寫Decorator函數了。

2.2、Decorator的編寫

在本文中,Decorator主要是對方法進行修飾,主要代碼如下:
decorator.js

const actionDecorator = (target, name, descriptor) => {
  const fn = descriptor.value;
  descriptor.value = function(...args) {
    console.log('調用了修飾器的方法');
    return fn.apply(this, args);
  };
  return descriptor;
};

store.js

const module = {
  state: () => ({}),
  actions: {
    @actionDecorator
    someAction() {/** 業務代碼 **/ },
  },
};

可以看到,actionDecorator修飾器的三個入參和Object.defineProperty一樣,通過對module.actions.someAction函數的修飾,實現在編譯時重寫someAction方法,在調用方法時,會先執行console.log('調用了修飾器的方法');,而后再調用方法里的業務代碼。對于多個功能的實現,比如存儲數據,發送廣播,打印日志和數據埋點,增加多個Decorator即可。

3、Vuex

Vuex本身可以用subscribe和subscribeAction訂閱相應的mutation和action,但只支持同步執行,而Weex的storage存儲是異步操作,因此需要對Vuex的現有方法進行擴展,以滿足相應的需求。

3.1、修飾action

在Vuex里,可以通過commit mutation或者dispatch action來更改state,而action本質是調用commit mutation。因為storage包含異步操作,在不破壞Vuex代碼規范的前提下,我們選擇修飾action來擴展功能。

storage使用回調函數來讀寫item,首先我們將其封裝成Promise結構:

storage.js

const storage = weex.requireModule('storage');
const handler = {
 get: function(target, prop) {
  const fn = target[prop];
  // 這里只需要用到這兩個方法
  if ([
   'getItem',
   'setItem'
  ].some(method => method === prop)) {
   return function(...args) {
    // 去掉回調函數,返回promise
    const [callback] = args.slice(-1);
    const innerArgs = typeof callback === 'function' ? args.slice(0, -1) : args;
    return new Promise((resolve, reject) => {
     fn.call(target, ...innerArgs, ({result, data}) => {
      if (result === 'success') {
       return resolve(data);
      }
      // 防止module無保存state而出現報錯
      return resolve(result);
     })
    })
   }
  }
  return fn;
 },
};
export default new Proxy(storage, handler);

通過Proxy,將setItem和getItem封裝為promise對象,后續使用時可以避免過多的回調結構。

現在我們把storage的setItem方法寫入到修飾器:

decorator.js

import storage from './storage';
// 加個rootKey,防止rootState的namespace為''而導致報錯
// 可自行替換為其他字符串
import {rootKey} from './constant';
const setState = (target, name, descriptor) => {
  const fn = descriptor.value;
  descriptor.value = function(...args) {
    const [{state, commit}] = args;
    // action為異步操作,返回promise,
    // 且需在狀態修改為fulfilled時再將state存儲到storage
    return fn.apply(this, args).then(async data => {
      // 獲取store的moduleMap
      const rawModule = Object.entries(this._modulesNamespaceMap);
      // 根據當前的commit,查找此action所在的module
      const moduleMap = rawModule.find(([, module]) => {
        return module.context.commit === commit;
      });
      if (moduleMap) {
        const [key, {_children}] = moduleMap;
        const childrenKeys = Object.keys(_children);
        // 只獲取當前module的state,childModule的state交由其存儲,按module存儲數據,避免存儲數據過大
        // Object.fromEntries可使用object.fromentries來polyfill,或可用reduce替代
        const pureState = Object.fromEntries(Object.entries(state).filter(([stateKey]) => {
          return !childrenKeys.some(childKey => childKey === stateKey);
        }));
        await storage.setItem(rootKey + key, JSON.stringify(pureState));
      }
      // 將data沿著promise鏈向后傳遞
      return data;
    });
  };
  return descriptor;
};
export default setState;

完成了setState修飾器功能以后,就可以裝飾action方法了,這樣等action返回的promise狀態修改為fulfilled后調用storage的存儲功能,及時保存數據狀態以便在新開Weex頁面加載最新數據。

store.js

import setState from './decorator';
const module = {
  state: () => ({}),
  actions: {
    @setState
    someAction() {/** 業務代碼 **/ },
  },
};

3.2、讀取module數據

完成了存儲數據到storage以后,我們還需要在新開的Weex頁面實例能自動讀取數據并初始化Vuex的狀態。在這里,我們使用Vuex的plugins設置來完成這個功能。

首先我們先編寫Vuex的plugin:

plugin.js

import storage from './storage';
import {rootKey} from './constant';
const parseJSON = (str) => {
  try {
    return str ? JSON.parse(str) : undefined;
  } catch(e) {}
  return undefined;
};
const getState = (store) => {
  const getStateData = async function getModuleState(module, path = []) {
    const {_children} = module;
    // 根據path讀取當前module下存儲在storage里的數據
    const data = parseJSON(await storage.getItem(`${path.join('/')}/`)) || {};
    const children = Object.entries(_children);
    if (!children.length) {
      return data;
    }
    // 剔除childModule的數據,遞歸讀取
    const childModules = await Promise.all(
      children.map(async ([childKey, child]) => {
       return [childKey, await getModuleState(child, path.concat(childKey))];
      })
    );
    return {
      ...data,
      ...Object.fromEntries(childModules),
    }
  };
  // 讀取本地數據,merge到Vuex的state
  const init = getStateData(store._modules.root, [rootKey]).then(savedState => {
    store.replaceState(merge(store.state, savedState, {
      arrayMerge: function (store, saved) { return saved },
      clone: false,
    }));
  });
};
export default getState;

以上就完成了Vuex的數據按照module讀取,但Weex的IOS/Andriod中的storage存儲是異步的,為防止組件掛載以后發送請求返回的數據被本地數據覆蓋,需要在本地數據讀取并merge到state以后再調用new Vue,這里我們使用一個簡易的interceptor來攔截:

interceptor.js

const interceptors = {};
export const registerInterceptor = (type, fn) => {
  const interceptor = interceptors[type] || (interceptors[type] = []);
  interceptor.push(fn);
};
export const runInterceptor = async (type) => {
  const task = interceptors[type] || [];
  return Promise.all(task);
};

這樣plugin.js中的getState就修改為:

import {registerInterceptor} from './interceptor';
const getState = (store) => {
  /** other code **/
  const init = getStateData(store._modules.root, []).then(savedState => {
    store.replaceState(merge(store.state, savedState, {
      arrayMerge: function (store, saved) { return saved },
      clone: false,
    }));
  });
  // 將promise放入攔截器
  registerInterceptor('start', init);
};

store.js

import getState from './plugin';
import setState from './decorator';
const rootModule = {
  state: {},
  actions: {
    @setState
    someAction() {/** 業務代碼 **/ },
  },
  plugins: [getState],
  modules: {
    /** children module**/
  }
};

app.js

import {runInterceptor} from './interceptor';
// 待攔截器內所有promise返回resolved后再實例化Vue根組件
// 也可以用Vue-Router的全局守衛來完成
runInterceptor('start').then(() => {
  new Vue({/** other code **/});
});

這樣就實現了Weex頁面實例化后,先讀取storage數據到Vuex的state,再實例化各個Vue的組件,更新各自的module狀態。

4、TODO

通過Decorator實現了Vuex的數據分模塊存儲到storage,并在Store實例化時通過plugin分模塊讀取數據再merge到state,提高數據存儲效率的同時實現與業務邏輯代碼的解耦。但還存在一些可優化的點:

1、觸發action會將所有module中的所有state全部,只需保存所需狀態,避免存儲無用數據。

2、對于通過registerModule注冊的module,需支持自動讀取本地數據。

3、無法通過_modulesNamespaceMap獲取namespaced為false的module,需改為遍歷_children。

在此不再展開,將在后續版本中實現。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持創新互聯。


當前標題:利用Dectorator分模塊存儲Vuex狀態的實現
URL地址:http://www.xueling.net.cn/article/geopei.html

其他資訊

在線咨詢
服務熱線
服務熱線:028-86922220
TOP
主站蜘蛛池模板: 一本到在线观看视频 | 91精品免费在线观看 | 六月婷婷久香在线视频 | 亚洲大乳大丰满中文字幕 | 黄色av一级片 | 久草一级片 | 国产在线观 | 国产精品久久国产精品 | 成人激情在线观看 | 成人国产精品入口免费视频 | 中文字幕亚洲综合久久久软件 | 国产综合影院 | 亚洲午夜福利AV一区二区无码 | 一级黄色免费视频 | 日本韩国最新免费观看 | 草1024榴社区成人影院 | 中文字幕在线观看国产推理片 | 免费av网址在线观看 | 善良的邻居在线观看 | 久久亚洲色WWW成人男男 | 免费人成在线观看视频无码 | 国产欧美日韩在线观看一区二区 | 有码+日韩+在线观看 | 国产日产一区二区三区久久久久久 | 成人欧美一区二区三区色青冈 | 成人午夜精品无码区久久 | 天天色图综合网 | 亚州日本乱码一区二区三区 | 网站大全免费网址 | 国产一二三视频 | 成人三级做爰av | 欧美一级爱爱视频 | 久久精品国产视频 | 91高清视频在线免费观看 | 国产又粗又猛又爽的视频A片 | 国产精品免费视频久久久 | 精品亚洲AⅤ无码午夜在线网站 | 人妻激情偷乱一区二区三区 | 免费又粗又硬进去好爽A片视频 | 日本黄色五级片 | 天天色天天色天天色 |