(自用)vuex的使用,getters,actions声明与使用

import request from "@/api/Interface.js";

//schema转json
function schemaToTableData(modelData) {
  let dfs = (val, tableData) => {
    for (let key in val) {
      let element = val[key];
      let obj = {
        id: key,
        key: key,
        type: element.type,
        desc: element.description ? element.description : key,
        info: element.type,
      };
      if (element.properties) {
        obj.children = [];
        dfs(element.properties, obj.children);
      } else if (element.items) {
        obj.info = element.type + `[${element.items.type}]`;
        if (element.items.properties) {
          obj.children = [];
          dfs(element.items.properties, obj.children);
        }
      }

      tableData.push(obj);
    }
  };
  let arr = [];
  dfs(modelData, arr);
  return arr;
}

const flushTime = 30 * 1000; //数据缓存时间

const state = {
  tableModelList: [],
  timestamp: new Date().getTime() - flushTime,
};

const getters = {
  schemaToTableData: (state) => (tableId) => {
    let arr = state.tableModelList.filter((item) => {
      return item.tableId === tableId;
    });
    return arr.length > 0 ? schemaToTableData(arr[0].properties) : [];
  },
};

const mutations = {};

const actions = {
  async fetch({ state }, forceRefresh = false) {
    let n = new Date().getTime();
    if (forceRefresh || n - state.timestamp > flushTime) {
      let res = await request.tableModelList();
      state.tableModelList = res.data.rows;
      state.timestamp = n;
    }
  },
};

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


...mapState("tableModel", ["tableModelList"]),

this.$store.getters["tableModel/schemaToTableData"](id)

...mapActions("tableModel", { tableModelFetch: "fetch" }),

posted @ 2022-10-10 17:25  yoona-lin  阅读(49)  评论(0编辑  收藏  举报