全栈开发实战小草看书之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端(八)主入口】