Vue3 開發(fā)拒絕 CV, 快使用 CRUD
開發(fā)管理后臺基本是企業(yè)的日常需求, 基本每個前臺項目都必有一個后臺項目跟著, 雖然是必需品, 但是大家好像有不是那么在意他, 畢竟只有管理員用。
crud-vue通過簡單的JSON配置即可實現(xiàn)完整的"增刪改查".
注意: crud-vue是基于ant-design-vue的, 所以更進(jìn)一步的開發(fā)中,可直接使用ant的組件
安裝
yarn add crud-vue
復(fù)制代碼
使用
下面是一個簡單的表格, 只需要配置columns和done字段.
columns就是"ant"組件庫中 table 組件的配置, 用來配置列.
done是"crud-vue"定義的字段, 值是個函數(shù), 用來格式化接口返回數(shù)據(jù), 函數(shù)返回{total:10,list:[{xx:1}]}這樣的數(shù)據(jù)表格就會顯示:
<script setup lang="ts">
import crud,{defineR} from 'crud-vue';
const primaryKey = 'id';
const r = defineR({
columns: [
{
title: 'name',
dataIndex: 'name',
},
{
title: '操作',
key: 'operation',
width: 250,
},
],
async done() {
const { data } = await http('/role');
return { list: data.list, total: data.total };
},
});
</script>
<template>
<crud :primaryKey="primaryKey" :r="r"></crud>
</template>
復(fù)制代碼
API
通過配置"crud-vue"組件的"c/u/r/d"4 個字段實現(xiàn)"增刪改查".
primaryKey(主鍵)
必填項, ant 中的a-table需要, 選用數(shù)據(jù)中的能"表示唯一的id"字段即可.
image
r(讀取)
必填項, 主要配置"表格"和"數(shù)據(jù)", 這里的表格實際就是??ant的table組件, 使用defineR函數(shù)定義.
const r = defineR({
// 列配置
columns: [{ title: 'name', dataIndex: 'name' }],
// 篩選條件配置
conditionItems: [{ name: 'name', is: 'a-input' }],
// 列表接口數(shù)據(jù)處理
async done() {
const { data } = await http('/user');
return { list: data.xxList, total: data.xxTotal };
},
});
復(fù)制代碼
查看"r"的完整文檔[1]
c(新增)
非必填, 用來構(gòu)造"新建"表單,用defineC函數(shù)來定義.
const c = defineC({
async before() {
await Promise.all([getRoleOptions(), getDepartmentOptions(), getPositionOptions()]);
},
async done(formData) {
const { status, data } = await http.post('/user', formData);
return [200 === status, data.msg];
},
formProps: { labelCol: { span: 2 } },
items: () => [
{ is: 'a-input', name: 'userName', label: '賬號', rules: [{ required: true, message: '必填項' }] },
{ is: 'a-input', name: 'realName', label: '姓名' },
復(fù)制代碼
查看"c"的完整文檔[2]
u(編輯)
非必填, 用來構(gòu)造"編輯"表單,用defineU函數(shù)來定義.基本和"c"的配置一樣.
查看"u"完整的文檔[3]
d(刪除)
非必填, 用來配置"刪除操作",用defineD函數(shù)來定義. d暫只有一個屬性done:
done
必填項, done是個函數(shù), 點擊"刪除"按鈕后觸發(fā), 函數(shù)內(nèi)需要寫請求刪除接口的邏輯.
const d = defineD({
async done(idList) {
// 判斷idList長度區(qū)分是否批量刪除
// 批量刪除
if (1 < idList.length) {
const { data, status } = await http.delete('/user/' + idList.join(','));
return [200 === status, data.msg];
} else {
// 刪除一條
const { data, status } = await http.delete('/user/' + idList[0]);
return [200 === status, data.msg];
}
},
});
復(fù)制代碼
可以通過done的參數(shù)來判斷是批量刪除還是單行刪除.
特別注意
- done必須是一個返回"promise"的函數(shù), 也可以用"async", 其返回值也是"promise".
- done函數(shù)的返回值必須是[boolean,string?]格式, "boolean"用來表示是否操作成功, "string"是選填,是成功/失敗后消息框顯示的文字, 如果不填, 不進(jìn)行消息顯示.