collect.js 1.42 KB
import { fetchCollectList, addCollect, delCollect } from '@/api/menu/menu';

const GET_COLLECT_LIST = 'GET_COLLECT_LIST';
const ADD_COLLECT_LIST = 'ADD_COLLECT_LIST';
const DEL_COLLECT_LIST = 'DEL_COLLECT_LIST';

let fetch = 0;

const state = () => ({
  collectList: [],
});

const getters = {
  collectList: state => state.collectList,
};

const actions = {
  fetchCollectList({ commit }) {
    if (fetch) return;
    fetch++;
    return fetchCollectList()
      .then(res => {
        fetch--;
        const data = res.data;
        commit(GET_COLLECT_LIST, data);
        return res;
      })
      .catch(err => {
        console.error(err);

        fetch--;
      });
  },
  addCollect({ commit, getters }, entity) {
    return addCollect({
      data: { ...entity, sortId: getters.collectList.length + 1 },
    }).then(res => {
      commit(ADD_COLLECT_LIST, entity.menuId);
    });
  },
  delCollect({ commit }, entity) {
    return delCollect({
      params: entity,
    }).then(res => {
      commit(DEL_COLLECT_LIST, entity.id);
    });
  },
};

const mutations = {
  [GET_COLLECT_LIST](state, list) {
    state.collectList = list;
  },
  [ADD_COLLECT_LIST](state, id) {
    state.collectList.push({
      menuId: id,
    });
  },
  [DEL_COLLECT_LIST](state, id) {
    state.collectList = state.collectList.filter(
      item => item.menuId.toString() !== id
    );
  },
};

export default {
  state,
  getters,
  actions,
  mutations,
};