Vue3 開發拒絕 CV- 快使用 CRUD
開發管理後臺基本是企業的日常需求, 基本每個前臺項目都必有一個後臺項目跟着, 雖然是必需品, 但是大家好像有不是那麼在意他, 畢竟只有管理員用, 今天我們講一下 "增刪改查" 組件:crud-vue
.
crud-vue
通過簡單的 JSON 配置即可實現完整的 "增刪改查".
注意: crud-vue 是基於 ant-design-vue 的, 所以更進一步的開發中, 可直接使用 ant 的組件
安裝
yarn add crud-vue
複製代碼
使用
下面是一個簡單的表格, 只需要配置columns
和done
字段.
columns
就是 "ant" 組件庫中 table 組件的配置, 用來配置列.
done
是 "crud-vue" 定義的字段, 值是個函數, 用來格式化接口返回數據, 函數返回{total:10,list:[{xx:1}]}
這樣的數據表格就會顯示.
<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>
複製代碼
API
通過配置 "crud-vue" 組件的 "c/u/r/d"4 個字段實現" 增刪改查 ".
primaryKey(主鍵)
必填項, ant 中的a-table
需要, 選用數據中的能 " 表示唯一的 id" 字段即可.
image
r(讀取)
必填項, 主要配置 "表格" 和 "數據", 這裏的表格實際就是🐜ant 的 table 組件, 使用defineR
函數定義.
const r = defineR({
// 列配置
columns: [{ title: 'name', dataIndex: 'name' }],
// 篩選條件配置
conditionItems: [{ name: 'name', is: 'a-input' }],
// 列表接口數據處理
async done() {
const { data } = await http('/user');
return { list: data.xxList, total: data.xxTotal };
},
});
複製代碼
查看 "r" 的完整文檔 [1]
c(新增)
非必填, 用來構造 "新建" 表單, 用defineC
函數來定義.
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: '姓名' },
複製代碼
查看 "c" 的完整文檔 [2]
u(編輯)
非必填, 用來構造 "編輯" 表單, 用defineU
函數來定義. 基本和 "c" 的配置一樣.
查看 "u" 完整的文檔 [3]
d(刪除)
非必填, 用來配置 "刪除操作", 用defineD
函數來定義. d
暫只有一個屬性done
:
done
必填項, done
是個函數, 點擊 "刪除" 按鈕後觸發, 函數內需要寫請求刪除接口的邏輯.
const d = defineD({
async done(idList) {
// 判斷idList長度區分是否批量刪除
// 批量刪除
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];
}
},
});
複製代碼
可以通過 done 的參數來判斷是批量刪除還是單行刪除.
特別注意
-
done
必須是一個返回 "promise"的函數, 也可以用"async", 其返回值也是"promise". -
done
函數的返回值必須是[boolean,string?]
格式, "boolean" 用來表示是否操作成功, "string" 是選填, 是成功 / 失敗後消息框顯示的文字, 如果不填, 不進行消息顯示.
關於本文
作者:鐵皮飯盒
https://juejin.cn/post/7127169214879629320
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源:https://mp.weixin.qq.com/s/53GFWWPI1WNAcLLAz5yBog