使用Vue3+ts?開發(fā)ProTable源碼教程示例
前臺實現(xiàn)
實現(xiàn)效果

技術(shù)棧
vue3 + typescript + element-plus
使用方法
<template>
<el-tabs type="border-card" v-model="activeName">
<el-tab-pane
:label="item.label"
v-for="(item, index) in templateConfig"
:key="index" :name="item.name"
lazy
>
<!--所有的 slot內(nèi)容都在表格內(nèi)部處理好, columnsType進(jìn)行區(qū)分-->
<pro-table
:columns="item.columns"
:type="item.name"
:request-url="requestUrl"
>
</pro-table>
</el-tab-pane>
</el-tabs>
</template>
<script lang="ts" setup>
import { ref } from 'vue'
import ProTable from './components/ProTable/index.vue'
import { ColumnProps, RequestUrl } from './components/ProTable/types'
import { projectConfig, projectConfigBatchDelete } from './service/api'
const activeName = ref('user')
interface TemplateConfig {
name: string
label: string
columns: ColumnProps[],
}
const requestUrl: RequestUrl = {
create: projectConfig,
list: projectConfig,
update: projectConfig,
destroy: projectConfig,
batchDelete: projectConfigBatchDelete
}
const templateConfig = ref<TemplateConfig[]>([
{
label: 'ProTable',
name: 'user',
columns: [
{
key: 'userName',
title: '用戶名',
searchType: 'el-input'
},
{
key: 'password',
title: '密碼',
searchType: 'el-input'
},
{
key: 'email',
title: '郵箱',
searchType: 'el-input'
},
{
key: 'phone',
title: '手機號',
searchType: 'el-input'
},
{
key: 'role',
title: '角色',
searchType: 'z-select',
attrs: {
options: [
{
label: '管理員',
value: 'admin'
},
{
label: '普通用戶',
value: 'user'
}
]
}
},
{
key: 'status',
title: '狀態(tài)',
searchType: 'z-select',
attrs: {
options: [
{
label: '啟用',
value: 1
},
{
label: '禁用',
value: 0
}
]
},
columnType: 'status'
},
{
key: 'hasUseArray',
title: '是否使用數(shù)組參數(shù)?',
search: false,
searchType: 'useExpandField',
show: false,
add: false
},
{
key: 'arrayParams',
title: '數(shù)組參數(shù)',
searchType: 'z-array',
search: false,
width: 120,
add: false,
show: false
},
{
key: 'hasUseArray',
title: '是否使用JSON參數(shù)?',
search: false,
searchType: 'useExpandField',
show: false,
add: false
},
{
key: 'jsonParams',
title: 'JSON參數(shù)',
searchType: 'z-json',
search: false,
width: 120,
add: false,
show: false
},
{
key: 'createdAt',
title: '創(chuàng)建時間',
width: 180,
searchType: 'el-date-picker',
add: false
},
{
key: 'updatedAt',
title: '更新時間',
width: 180,
searchType: 'el-date-picker',
add: false
},
{
key: 'action',
title: '操作',
search: false,
add: false,
width: 150
}
]
}
])
</script>
<style lang="less">
</style>
ProTable 設(shè)計思路
頁面整體分為5個區(qū)域,
- 表單搜索區(qū)域
- 表格功能按鈕區(qū)域
- 表格右上角操作區(qū)域
- 表格主題區(qū)域
- 表格分頁區(qū)域
要考慮的問題?
- 那些區(qū)域是要支持傳入slot的?
- 表格原有的slot是否要交給用戶來傳遞,還是在內(nèi)部進(jìn)行封裝?如
colum是狀態(tài)的時候需要映射成tag,是數(shù)組類型的時候映射成表格,是json的時候需要點擊查看詳情?假設(shè)每個表格都要處理的的話就太麻煩,我們希望通過一個字段來控制它。 - 有
column的某一列是否需要復(fù)制的功能? - 列字段需要編輯的功能?
實現(xiàn)的過程中有哪些細(xì)節(jié)?
- 表格的高度,把可表格可視區(qū)域的大小交給用戶自己來控制,把批量操作按鈕放在最下面(
fixed定位)。這樣用戶可以在最大區(qū)域內(nèi)看到表格的內(nèi)容。
編碼風(fēng)格
- 組件上面屬性如果超過三個,就換行
- eslint使用的是
standard風(fēng)格。
css 小知識
<div class='box'> <div class='z'></div> </div>
*{
box-sizing: border-box;
}
.box{
display: inline-block;
vertical-align: top;
}
.z{
height: 32px;
border: 1px solid;
width: 100px;
display: inline-block;
}
如果把盒子變成了行內(nèi)元素之后,若其內(nèi)部還是行內(nèi)元素,那么就會產(chǎn)生間隙,就會導(dǎo)致其高度與父元素高度不同。如下。

解決方法也很簡單,則需要設(shè)置其子元素的vertical-align屬性,或者設(shè)置font-size: 0,其根本原因是因為中間的文本元素也占位置。再或者不使用inline-block,換做inline-flex屬性完全沒有問題,因為在element-plus組件庫中也大量的使用了這個屬性,兼容性也很nice。
這個幾個解決方法很早就知道了,就是關(guān)于vertical-algin這個,以及與line-height的關(guān)系還是有點模糊,一直也沒去深究。

放兩篇文章
還有聯(lián)想到baseline這個東西在flex,align-items屬性:交叉軸上的一個屬性很像。
表格操作
- 添加數(shù)據(jù)之后,重新獲取數(shù)據(jù)的時候
pageIndex要重置為1,刪除數(shù)據(jù)的時候也是一樣。 - 編輯數(shù)據(jù)的時候,
pageIndex不變,還是當(dāng)前頁碼。 - 總結(jié)下來,就是當(dāng)數(shù)據(jù)條數(shù)會發(fā)生改變的時候,都會重置
pageIndex為1。當(dāng)用戶操作不會影響數(shù)據(jù)總條數(shù)的時候,pageSize還維持當(dāng)前不變。
小結(jié)
- 使用了一個庫,可以監(jiān)聽dom元素大小的變化,resize-observer-polyfill。
- 在 3.x 中,如果一個元素同時定義了
v-bind="object"和一個相同的獨立 attribute。開發(fā)者可以自己選擇要保留哪一個。
文檔地址# v-bind 合并行為
參考文章
JavaScript API——ResizeObserver 的使用
后期功能擴展
- 字段之間有關(guān)聯(lián)關(guān)系情況的處理,暫時還沒想好。
- 擴展一下
slot - 等等。。
迭代中....

后臺實現(xiàn)
數(shù)據(jù)庫 mysql
我這里使用的是 xampp安裝的,我們來查看一下版本。這是什么版本?假的吧,真的到10了嗎? 先不管了,能用就行。

建表
CREATE TABLE `project_config` ( `id` int NOT NULL AUTO_INCREMENT COMMENT '主鍵', `type` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '配置類型', `value` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '配置的json字符串', `created_at` datetime NOT NULL, `updated_at` datetime NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 65 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = COMPACT;
新建項目
npm init egg --type=simple
項目目錄大致如下所示,

RESTful 風(fēng)格的 URL 定義

Sequelize
npm install --save egg-sequelize mysql2
- 在
config/plugin.js中引入 egg-sequelize 插件, 這里我們引入了一個庫egg-cors來幫我們實現(xiàn)cors。
'use strict';
/** @type Egg.EggPlugin */
exports.sequelize = {
enable: true,
package: 'egg-sequelize',
};
exports.cors = {
enable: true,
package: 'egg-cors',
};
- 在
config/config.default.js中編寫 sequelize 配置
/* eslint valid-jsdoc: "off" */
'use strict';
/**
* @param {Egg.EggAppInfo} appInfo app info
*/
module.exports = appInfo => {
/**
* built-in config
* @type {Egg.EggAppConfig}
**/
const config = exports = {};
// use for cookie sign key, should change to your own and keep security
config.keys = appInfo.name + '_1655529530112_7627';
// add your middleware config here
config.middleware = [];
config.security = {
csrf: {
enable: false,
ignoreJSON: true,
},
};
config.cors = {
origin: '*',
allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH',
};
// add your user config here
const userConfig = {
// myAppName: 'egg',
};
// sequelize
const sequelize = {
dialect: 'mysql',
host: '127.0.0.1',
port: 3306,
username: 'root',
password: '123456',
database: 'test_database',
timezone: '+08:00',
dialectOptions: {
dateStrings: true,
typeCast: true,
},
define: {
freezeTableName: true, // 模型名強制和表明一致
underscored: true, // 字段以下劃線(_)來分割(默認(rèn)是駝峰命名風(fēng)格)
},
};
return {
...config,
...userConfig,
sequelize,
};
};
1、時間格式化
類型需要采用:Sequelize.DATE
初始化Sequelize的時候傳入dialectOptions參數(shù),及timezone
timezone: '+08:00', // 改為標(biāo)準(zhǔn)時區(qū)
dialectOptions: {
dateStrings: true,
typeCast: true,
},
下面就開始編寫
controller
對這塊需要安裝lodash,懂的都懂。
controller/ProjectConfig.js
'use strict';
const { success } = require('../utils/res');
const { omit, pick } = require('lodash');
const Controller = require('egg').Controller;
class ProjectConfigController extends Controller {
async index() {
const { ctx } = this;
const { pageSize, pageIndex } = ctx.query;
const { Op, fn, col, where, literal } = this.app.Sequelize;
// 固定的查詢參數(shù)
const stableQuery = pick(ctx.query, [ 'type', 'createdAt', 'updatedAt' ]);
const stableQueryArgs = Object.keys(stableQuery)
.filter(key => Boolean(stableQuery[key]))
.map(key => {
return {
[key]: stableQuery[key],
};
});
const whereCondition = omit(ctx.query, [ 'pageIndex', 'pageSize', 'type', 'createdAt', 'updatedAt' ]);
// 需要模糊查詢的參數(shù)
const whereArgs = Object.keys(whereCondition)
.filter(key => Boolean(whereCondition[key]))
.map(key => {
return where(fn('json_extract', col('value'), literal(`\'$.${key}\'`)), {
[Op.like]: `%${whereCondition[key]}%`,
});
});
const query = {
where: {
[Op.and]: [
...stableQueryArgs,
...whereArgs,
],
},
order: [
[ 'createdAt', 'DESC' ],
],
limit: Number(pageSize), // 每頁顯示數(shù)量
offset: (pageIndex - 1) * pageSize, // 當(dāng)前頁數(shù)
};
const data = await ctx.model.ProjectConfig.findAndCountAll(query);
ctx.body = success(data);
}
async create() {
const { ctx } = this;
const { type, value } = ctx.request.body;
const data = await ctx.model.ProjectConfig.create({ type, value });
ctx.body = success(data);
}
async update() {
const { ctx } = this;
const { type, value } = ctx.request.body;
const { id } = ctx.params;
const data = await ctx.model.ProjectConfig.update({ type, value }, { where: { id } });
ctx.body = success(data);
}
async destroy() {
const { ctx } = this;
const { id } = ctx.params;
console.log(id);
const data = await ctx.model.ProjectConfig.destroy({ where: { id } });
ctx.body = success(data);
}
async batchDestroy() {
const { ctx } = this;
const { ids } = ctx.request.body;
console.log(ids);
const { Op } = this.app.Sequelize;
const data = await ctx.model.ProjectConfig.destroy({
where: {
id: {
[Op.in]: ids,
},
},
});
ctx.body = success(data);
}
}
module.exports = ProjectConfigController;
模糊查詢
SELECT json_extract(字段名,'$.json結(jié)構(gòu)') FROM 表名;
sequelize高級查詢
Post.findAll({
where: sequelize.where(sequelize.fn('char_length', sequelize.col('content')), 7)
});
// SELECT ... FROM "posts" AS "post" WHERE char_length("content") = 7
中文文檔,英文看的吃力,看中文的也無妨,不寒磣。^_^
model
model/project_config.js
'use strict';
module.exports = app => {
const { STRING, INTEGER, TEXT, DATE } = app.Sequelize;
const ProjectConfig = app.model.define('project_config', {
id: { type: INTEGER, primaryKey: true, autoIncrement: true },
type: { type: STRING },
value: {
type: TEXT,
get() {
return this.getDataValue('value') ? JSON.parse(this.getDataValue('value')) : null;
},
set(value) {
this.setDataValue('value', JSON.stringify(value));
},
},
createdAt: { type: DATE },
updatedAt: { type: DATE },
});
return ProjectConfig;
};
router.js
'use strict';
/**
* @param {Egg.Application} app - egg application
*/
module.exports = app => {
const { router, controller } = app;
router.get('/api/projectConfig', controller.projectConfig.index);
router.post('/api/projectConfig', controller.projectConfig.create);
router.put('/api/projectConfig/:id', controller.projectConfig.update);
router.delete('/api/projectConfig/:id', controller.projectConfig.destroy);
router.post('/api/projectConfig/batchDelete', controller.projectConfig.batchDestroy);
};
API 文檔 Apifox
先快速測試一把,然后去對前端代碼。

ts用到的一些
- 在類型別名(type alias)的聲明中可以使用
keyof、typeof、in等關(guān)鍵字來進(jìn)行一些強大的類型操作
interface A {
x: number;
y: string;
}
// 拿到 A 類型的 key 字面量枚舉類型,相當(dāng)于 type B = 'x' | 'y'
type B = keyof A;
const json = { foo: 1, bar: 'hi' };
// 根據(jù) ts 的類型推論生成一個類型。此時 C 的類型為 { foo: number; bar: string; }
type C = typeof json;
// 根據(jù)已有類型生成相關(guān)新類型,此處將 A 類型的所有成員變成了可選項,相當(dāng)于 type D = { x?: number; y?: string; };
type D = {
[T in keyof A]?: A[T];
};
在比如用一個聯(lián)合類型來約束對象的key,用interface我就沒實現(xiàn),貌似.
export type FormItemType = 'el-input' | 'z-select' | 'el-date-picker'
// 目前發(fā)現(xiàn) interface 的key 只能是三種 string number symbol keyof any
type IPlaceholderMapping = {
[key in FormItemType]: string
}
export const placeholderMapping: IPlaceholderMapping = {
'el-input': '請輸入',
'z-select': '請選擇',
'el-date-picker': '請選擇日期'
}
倉庫地址
以上就是使用Vue3+ts 開發(fā)ProTable源碼教程示例的詳細(xì)內(nèi)容,更多關(guān)于Vue3+ts 開發(fā)ProTable的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
vue addRoutes實現(xiàn)動態(tài)權(quán)限路由菜單的示例
本篇文章主要介紹了vue addRoutes實現(xiàn)動態(tài)權(quán)限路由菜單的示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-05-05
vue 調(diào)用 RESTful風(fēng)格接口操作
這篇文章主要介紹了vue 調(diào)用 RESTful風(fēng)格接口操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-08-08
vue中動態(tài)修改img標(biāo)簽中src的方法實踐
本文主要介紹了vue中動態(tài)修改img標(biāo)簽中src的方法實踐,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-07-07
使用vue/cli出現(xiàn)defineConfig?is?not?function錯誤解決辦法
這篇文章主要給大家介紹了關(guān)于使用vue/cli出現(xiàn)defineConfig?is?not?function錯誤的解決辦法,當(dāng)我們在做打包配置的時候,出現(xiàn)了這個錯誤,需要的朋友可以參考下2023-11-11
vue項目報錯Extra?semicolon?(semi)問題及解決
這篇文章主要介紹了vue項目報錯Extra?semicolon?(semi)問題及解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-10-10
Vue3?實現(xiàn)驗證碼倒計時功能(刷新保持狀態(tài))
倒計時的運用場景是需要經(jīng)常用到的,但是根據(jù)業(yè)務(wù)的不同,好比手機驗證碼或者是郵箱驗證碼之類的,即使用戶跳轉(zhuǎn)到其它頁面或者刷新,再次回到登錄也,驗證碼的倒計時也得保持狀態(tài),下面通過本文給大家分享Vue3?驗證碼倒計時功能實現(xiàn),感興趣的朋友一起看看吧2022-08-08
利用Vite2和Vue3實現(xiàn)網(wǎng)站國際化的全過程
vite2已經(jīng)出來一段時間了,最近沒忍住嘗試了一下,這篇文章主要給大家介紹了關(guān)于利用Vite2和Vue3實現(xiàn)網(wǎng)站國際化的相關(guān)資料,需要的朋友可以參考下2021-08-08

