【全栈开发实战小草看书之Web端(七)Crud增删改查组合式API】

全栈开发实战小草看书之Web端(七)Crud增删改查组合式API

介绍

增删改查常用功能的封装,分为动态加载组件,列表页和编辑页等功能

代码文件(crud/index.js)

import { provide, inject, reactive, toRefs, watch, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useGet, usePost, useDelete } from "@/http";

export function useComponent() {
  const state = reactive({
    component: {
      id: 0,
      name: null,
    },
  });
  const open = (id, name) => {
    state.component.id = id;
    state.component.name = name;
  };
  const close = () => {
    state.component.id = 0;
    state.component.name = null;
  };

  return {
    ...toRefs(state),
    open,
    close,
  };
}

export function useList(api, state, mounted) {
  provide("api", api);

  var o = {
    table: null,
    ids: [],
    params: {
      current: 1,
      size: 10,
    },
    data: {
      records: [],
      total: 0,
    },
  };
  Object.assign(o, state);
  const s = reactive(o);

  const select = (selection) => {
    s.ids = selection.map((i) => i.id);
  };
  const list = async () => {
    s.data = await useGet(api, {
      params: s.params,
    });
  };
  const remove = (ids) => {
    ids = ids ?? s.ids;
    if (ids.length > 0) {
      ElMessageBox.confirm("确定要删除吗?")
        .then(async () => {
          await useDelete(`${api}/${ids}`);
          s.params.current = 1;
          await list();
        })
        .catch(() => {
          s.table.clearSelection();
        });
    } else {
      ElMessage.error("请选择记录");
    }
  };
  watch(s.params, list);
  onMounted(async () => {
    await list();
    if (mounted) {
      await mounted();
    }
  });

  return {
    state: s,
    select,
    list,
    remove,
  };
}

export function useEdit(context, state, mounted) {
  const api = inject("api");

  var o = {
    form: null,
    id: 0,
    data: {},
  };
  Object.assign(o, state);
  const s = reactive(o);

  const edit = async (id) => {
    id = id ?? s.id;
    if (id) {
      s.data = await useGet(`${api}/${id}`);
      if (!s.data) {
        ElMessage.error("该记录不存在");
      }
    } else {
      s.data = {};
    }
  };
  const save = (continued) => {
    s.form.validate(async (valid) => {
      if (valid) {
        await usePost(api, s.data);
        if (continued) {
          edit(0);
        } else {
          context.emit("close");
        }
      }
    });
  };
  onMounted(async () => {
    await edit();
    if (mounted) {
      await mounted();
    }
  });

  return {
    api,
    state: s,
    save,
  };
}

上一章 【全栈开发实战小草看书之Web端(六)Vue Router动态路由】
下一章 【全栈开发实战小草看书之Web端(八)主入口】

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值