溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

怎么使用Vue3+ts開發(fā)ProTable

發(fā)布時間:2023-05-20 14:44:13 來源:億速云 閱讀:128 作者:iii 欄目:編程語言

這篇文章主要介紹了怎么使用Vue3+ts開發(fā)ProTable的相關知識,內(nèi)容詳細易懂,操作簡單快捷,具有一定借鑒價值,相信大家閱讀完這篇怎么使用Vue3+ts開發(fā)ProTable文章都會有所收獲,下面我們一起來看看吧。

前臺實現(xiàn)

實現(xiàn)效果

怎么使用Vue3+ts開發(fā)ProTable

技術棧

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進行區(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 設計思路

頁面整體分為5個區(qū)域,

  • 表單搜索區(qū)域

  • 表格功能按鈕區(qū)域

  • 表格右上角操作區(qū)域

  • 表格主題區(qū)域

  • 表格分頁區(qū)域

要考慮的問題?

  • 那些區(qū)域是要支持傳入slot的?

  • 表格原有的slot是否要交給用戶來傳遞,還是在內(nèi)部進行封裝?如colum是狀態(tài)的時候需要映射成tag,是數(shù)組類型的時候映射成表格,是json的時候需要點擊查看詳情?假設每個表格都要處理的的話就太麻煩,我們希望通過一個字段來控制它。

  • column的某一列是否需要復制的功能?

  • 列字段需要編輯的功能?

實現(xiàn)的過程中有哪些細節(jié)?

  • 表格的高度,把可表格可視區(qū)域的大小交給用戶自己來控制,把批量操作按鈕放在最下面(fixed定位)。這樣用戶可以在最大區(qū)域內(nèi)看到表格的內(nèi)容。

編碼風格
  • 組件上面屬性如果超過三個,就換行

  • eslint使用的是standard風格。

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)生間隙,就會導致其高度與父元素高度不同。如下。

怎么使用Vue3+ts開發(fā)ProTable

解決方法也很簡單,則需要設置其子元素的vertical-align屬性,或者設置font-size: 0,其根本原因是因為中間的文本元素也占位置。再或者不使用inline-block,換做inline-flex屬性完全沒有問題,因為在element-plus組件庫中也大量的使用了這個屬性,兼容性也很nice。

這個幾個解決方法很早就知道了,就是關于vertical-algin這個,以及與line-height的關系還是有點模糊,一直也沒去深究。

怎么使用Vue3+ts開發(fā)ProTable

放兩篇文章

CSS vertical-align 屬性

還有聯(lián)想到baseline這個東西在flex,align-items屬性:交叉軸上的一個屬性很像。

flex布局語法教程詳解

表格操作
  • 添加數(shù)據(jù)之后,重新獲取數(shù)據(jù)的時候pageIndex要重置為1,刪除數(shù)據(jù)的時候也是一樣。

  • 編輯數(shù)據(jù)的時候,pageIndex不變,還是當前頁碼。

  • 總結(jié)下來,就是當數(shù)據(jù)條數(shù)會發(fā)生改變的時候,都會重置pageIndex1。當用戶操作不會影響數(shù)據(jù)總條數(shù)的時候,pageSize還維持當前不變。

小結(jié)
  • 使用了一個庫,可以監(jiān)聽dom元素大小的變化,resize-observer-polyfill。

  • 在 3.x 中,如果一個元素同時定義了 v-bind="object" 和一個相同的獨立 attribute。開發(fā)者可以自己選擇要保留哪一個。

文檔地址# v-bind 合并行為

參考文章

JavaScript API&mdash;&mdash;ResizeObserver 的使用

后期功能擴展
  • 字段之間有關聯(lián)關系情況的處理,暫時還沒想好。

  • 擴展一下slot

  • 等等。。

迭代中....

怎么使用Vue3+ts開發(fā)ProTable

后臺實現(xiàn)

數(shù)據(jù)庫 mysql

我這里使用的是 xampp安裝的,我們來查看一下版本。這是什么版本?假的吧,真的到10了嗎? 先不管了,能用就行。

怎么使用Vue3+ts開發(fā)ProTable

建表

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

項目目錄大致如下所示,

怎么使用Vue3+ts開發(fā)ProTable

RESTful 風格的 URL 定義

怎么使用Vue3+ts開發(fā)ProTable

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 =&gt; {
  /**
   * 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, // 字段以下劃線(_)來分割(默認是駝峰命名風格)
    },
  };
  return {
    ...config,
    ...userConfig,
    sequelize,
  };
};

1、時間格式化

類型需要采用:Sequelize.DATE

初始化Sequelize的時候傳入dialectOptions參數(shù),及timezone

timezone: '+08:00',  // 改為標準時區(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, // 當前頁數(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

先快速測試一把,然后去對前端代碼。

怎么使用Vue3+ts開發(fā)ProTable

ts用到的一些
  • 在類型別名(type alias)的聲明中可以使用 keyof、typeof、in 等關鍵字來進行一些強大的類型操作

interface A {
  x: number;
  y: string;
}
// 拿到 A 類型的 key 字面量枚舉類型,相當于 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ù)已有類型生成相關新類型,此處將 A 類型的所有成員變成了可選項,相當于 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”這篇文章的內(nèi)容就介紹到這里,感謝各位的閱讀!相信大家對“怎么使用Vue3+ts開發(fā)ProTable”知識都有一定的了解,大家如果還想學習更多知識,歡迎關注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI