惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

H
Help Net Security
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
博客园 - 【当耐特】
Microsoft Azure Blog
Microsoft Azure Blog
Google DeepMind News
Google DeepMind News
Apple Machine Learning Research
Apple Machine Learning Research
有赞技术团队
有赞技术团队
Y
Y Combinator Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
爱范儿
爱范儿
L
LangChain Blog
IT之家
IT之家
酷 壳 – CoolShell
酷 壳 – CoolShell
MongoDB | Blog
MongoDB | Blog
Hugging Face - Blog
Hugging Face - Blog
G
Google Developers Blog
T
Tailwind CSS Blog
Engineering at Meta
Engineering at Meta
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
宝玉的分享
宝玉的分享
博客园 - 三生石上(FineUI控件)
D
DataBreaches.Net
Recent Announcements
Recent Announcements
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More

青空之蓝

[青空之蓝-2023] - 色彩 | 青空之蓝 [青空之蓝-2022] - 平静 | 青空之蓝 [青空之蓝-2021] - 远望 | 青空之蓝 浅谈垃圾回收 | 青空之蓝 浅谈泛型擦除 | 青空之蓝 浅谈单点登录 | 青空之蓝 使用 Kotlin 编写 Spring 测试 | 青空之蓝 设计模式系列文章 | 青空之蓝 从零实现一个 Java 微框架 - IoC | 青空之蓝 从零实现一个 Java 微框架 - 前言 | 青空之蓝 浅谈 JVM:类加载 | 青空之蓝 浅谈 IO | 青空之蓝 浅谈并发:synchronized & ReentrantLock | 青空之蓝 浅谈并发:CAS & AQS | 青空之蓝 浅谈并发:ThreadLocal | 青空之蓝 浅谈并发:三大特性 | 青空之蓝 浅谈组合注解 & 注解别名 | 青空之蓝 [青空之蓝-2020]-迷茫 | 青空之蓝 Java 系列文章 | 青空之蓝 HTTP 系列文章 | 青空之蓝 浅谈 EatWhatYouKill | 青空之蓝 浅谈可扩展线程池 | 青空之蓝 聊聊写框架 | 青空之蓝 聊聊现状-[2020-09] | 青空之蓝 浅谈并发:锁 | 青空之蓝 浅谈并发:基础 | 青空之蓝 浅谈缓存 | 青空之蓝 无须定义类,Spring 快速注入 Json 参数 | 青空之蓝 浅谈 Proxy 和 Aop | 青空之蓝 从零实现一个 PHP 微框架 - 初始化请求 | 青空之蓝
为Vuex添加同步Action | 青空之蓝
Otstar Lin · 2019-11-16 · via 青空之蓝

为什么要添加同步 Action?

在某些操作中,如获取内存中的数据时,需要立即返回对应的值,而 Vuex 的 Action 规定了只能返回一个 Promise,这时,如果我们想获取返回值就需要使用 then 或者 await,代码就会变得不直观,而如果触发 Mutation 再从 State 获取值也是同理,所以如何能让 Action 不是异步的又能保持和 Vuex 的 Action 拥有一样的功能呢?

添加同步 Action

首先我们先看看 Vuex 的 Action 的结构是如何的:

const actions = {
  asyncAction(context, data) {
    // do soming...
  },
};
const actions = {
  asyncAction(context, data) {
    // do soming...
  },
};

可以看到,action 中传入了 context 和 data,所以我们添加的同步 action 也需要增加这两个参数,同时将 store 绑定到 action 的 this。

const actions = {
  asyncAction(context, data) {
    // do soming...
  },
};

export const syncActions = {
  // 同时导出,以便后续的操作
  syncActin(context, data) {
    // do soming...
    return val;
  },
};

//...

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations,
};
const actions = {
  asyncAction(context, data) {
    // do soming...
  },
};

export const syncActions = {
  // 同时导出,以便后续的操作
  syncActin(context, data) {
    // do soming...
    return val;
  },
};

//...

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations,
};

在 index.js 导入对应的模块和同步 actions 对象,同时导出修改过的同步 action,用于 mapSyncActions,并为每个同步 action 绑定 this 和注入参数。

import note, { syncActions as syncNote } from "./modules/note";
import { dispatchSync } from "./syncActions";

export const syncActions = {
  note: syncNote,
};

for (const nKey in syncActions) {
  let getters = {};
  for (const gKey of Object.keys(store.getters)) {
    let k = gKey.split("/");
    if (k[0] === nKey) {
      Object.defineProperty(getters, k[1], {
        get() {
          return store.getters[gKey];
        },
      });
    }
  }
  for (const iKey in syncActions[nKey]) {
    syncActions[nKey][iKey] = syncActions[nKey][iKey].bind(store, {
      state: store.state[nKey],
      rootState: store.state,
      commit: function (type, payload = null, options = null) {
        store.commit(nKey + "/" + type, payload, options);
      }.bind(store),
      dispatch: function (type, payload = null, options = { root: false }) {
        let t = options.root ? type : nKey + "/" + type;
        return store.dispatch(t, payload);
      }.bind(store),
      dispatchSync: function (type, payload = null, options = { root: false }) {
        let t = options.root ? type : nKey + "/" + type;
        return dispatchSync(t, payload);
      }.bind(store),
      rootGetters: store.getters,
      getters: getters,
    });
  }
}

store.syncActions = syncActions;
store.dispatchSync = dispatchSync;
import note, { syncActions as syncNote } from "./modules/note";
import { dispatchSync } from "./syncActions";

export const syncActions = {
  note: syncNote,
};

for (const nKey in syncActions) {
  let getters = {};
  for (const gKey of Object.keys(store.getters)) {
    let k = gKey.split("/");
    if (k[0] === nKey) {
      Object.defineProperty(getters, k[1], {
        get() {
          return store.getters[gKey];
        },
      });
    }
  }
  for (const iKey in syncActions[nKey]) {
    syncActions[nKey][iKey] = syncActions[nKey][iKey].bind(store, {
      state: store.state[nKey],
      rootState: store.state,
      commit: function (type, payload = null, options = null) {
        store.commit(nKey + "/" + type, payload, options);
      }.bind(store),
      dispatch: function (type, payload = null, options = { root: false }) {
        let t = options.root ? type : nKey + "/" + type;
        return store.dispatch(t, payload);
      }.bind(store),
      dispatchSync: function (type, payload = null, options = { root: false }) {
        let t = options.root ? type : nKey + "/" + type;
        return dispatchSync(t, payload);
      }.bind(store),
      rootGetters: store.getters,
      getters: getters,
    });
  }
}

store.syncActions = syncActions;
store.dispatchSync = dispatchSync;

然后,我们还要实现对应的 dispatch 方法和 mapActions 方法,来实现调用该 action,在 index.js 同级文件夹下添加一个 syncActions.js

import { syncActions } from "./index";

function addMethod(object, name, fn) {
  var old = object[name];
  object[name] = function () {
    if (fn.length === arguments.length) {
      return fn.apply(this, arguments);
    } else if (typeof old === "function") {
      return old.apply(this, arguments);
    }
  };
}

const mod = {};

addMethod(mod, "mapSyncActions", (map) => {
  let fn = {};
  let namespace = "";
  let action = "";
  for (let i = 0; i < map.length; i++) {
    [namespace, action] = map[i].split("/");
    if (syncActions[namespace]) {
      fn[action] = syncActions[namespace][action];
    }
  }
  return fn;
});

addMethod(mod, "mapSyncActions", (namespace, map) => {
  let fn = {};
  for (let i = 0; i < map.length; i++) {
    if (syncActions[namespace]) {
      fn[map[i]] = syncActions[namespace][map[i]];
    }
  }
  return fn;
});

export const mapSyncActions = mod.mapSyncActions;
export function dispatchSync(type, payload = null) {
  let namespace = "";
  let action = "";
  [namespace, action] = type.split("/");
  if (syncActions[namespace]) {
    return syncActions[namespace][action](payload);
  }
}
import { syncActions } from "./index";

function addMethod(object, name, fn) {
  var old = object[name];
  object[name] = function () {
    if (fn.length === arguments.length) {
      return fn.apply(this, arguments);
    } else if (typeof old === "function") {
      return old.apply(this, arguments);
    }
  };
}

const mod = {};

addMethod(mod, "mapSyncActions", (map) => {
  let fn = {};
  let namespace = "";
  let action = "";
  for (let i = 0; i < map.length; i++) {
    [namespace, action] = map[i].split("/");
    if (syncActions[namespace]) {
      fn[action] = syncActions[namespace][action];
    }
  }
  return fn;
});

addMethod(mod, "mapSyncActions", (namespace, map) => {
  let fn = {};
  for (let i = 0; i < map.length; i++) {
    if (syncActions[namespace]) {
      fn[map[i]] = syncActions[namespace][map[i]];
    }
  }
  return fn;
});

export const mapSyncActions = mod.mapSyncActions;
export function dispatchSync(type, payload = null) {
  let namespace = "";
  let action = "";
  [namespace, action] = type.split("/");
  if (syncActions[namespace]) {
    return syncActions[namespace][action](payload);
  }
}

如果要在 Vuex 模块中使用,只需要导入 syncActions.js 然后同 Vuex 的 action 调用一样即可。

import { dispatchSync } from "../syncActions";

let info = dispatchSync("note/listOperate", {
  operate: "get",
  storage: storage,
  path: path,
});
import { dispatchSync } from "../syncActions";

let info = dispatchSync("note/listOperate", {
  operate: "get",
  storage: storage,
  path: path,
});

若要在组件中使用,只需要同 mapActions 一样使用 mapSyncActions 即可,或者使用 dispatchSync。

import { mapSyncActions } from "./store/syncActions";

export default {
  methods: {
    ...mapSyncActions("note", ["listOperate"]),
    fun() {
      this.$store.dispatchSync("note/listOperate");
    },
  },
};
import { mapSyncActions } from "./store/syncActions";

export default {
  methods: {
    ...mapSyncActions("note", ["listOperate"]),
    fun() {
      this.$store.dispatchSync("note/listOperate");
    },
  },
};

结语

说实在搞这个其实没啥用,因为用到的机会其实也很小,只是当初我把 XK-Note 重构到 Vuex 时,不想修改太多的代码逻辑搞出来的,本文的实例具体可以查看 XK-Note。

为Vuex添加同步Action

https://blog.ixk.me/post/add-sync-action-for-vuex
  • 许可协议

    BY-NC-SA

  • 本文作者

    Otstar Lin

  • 发布于

    2019/11/16

转载或引用本文时请遵守许可协议,注明出处、不得用于商业用途!

为React添加简单的Store浅谈B+树