Skip to content

最佳实践

项目组织

推荐目录结构

src/
├── api/                      # API 接口
│   ├── system/
│   │   ├── user.ts
│   │   └── dict.ts
│   └── business/
│       └── order.ts
├── config/
│   └── pageTemplate/
│       ├── index.ts          # 初始化配置
│       ├── columns.ts        # 列配置注册
│       ├── forms.ts          # 表单配置注册
│       ├── search.ts         # 搜索配置注册
│       └── adapters.ts       # 自定义适配器
├── views/
│   └── system/
│       └── user/
│           ├── index.vue     # 页面组件
│           └── config.ts     # 页面配置(可选)
└── main.ts

配置集中管理

typescript
// src/config/pageTemplate/index.ts
import { setupPageTemplate } from "vue-admin-kit";
import { setupColumnConfigs } from "./columns";
import { setupFormConfigs } from "./forms";
import { setupSearchConfigs } from "./search";
import { CUSTOM_ADAPTERS } from "./adapters";

export function setupPageTemplateConfig() {
  // 初始化 PageTemplate
  setupPageTemplate({
    dependencies: {
      dictLoader: async (dictType) => {
        /* ... */
      },
      oss: {
        /* ... */
      },
      customAdapters: CUSTOM_ADAPTERS,
    },
  });

  // 注册配置
  setupColumnConfigs();
  setupFormConfigs();
  setupSearchConfigs();
}

配置复用

使用配置工具

将通用配置注册后按名称获取,避免重复定义:

typescript
// 注册
registerColumnConfigs([
  col("序号", { type: "seq", minWidth: 100 }),
  col("创建时间", { field: "createTime", sortable: true }),
  col("状态", { field: "status", dictType: "sys_status", displayType: "tag" }),
]);

// 使用
const columnsConfig = defineColumnsConfig([
  ...getColumnConfig(["序号", "客户名称", "状态", "创建时间"]),
]);

配置继承与覆盖

typescript
// 基础配置
const baseUserForm = [
  { type: "input", prop: "userName", label: "用户名", required: true },
  { type: "input", prop: "phone", label: "手机号" },
];

// 新增表单(继承基础配置)
const addFormConfig = defineFormConfig([
  ...baseUserForm,
  { type: "input", prop: "password", label: "密码", required: true },
]);

// 编辑表单(继承并覆盖)
const editFormConfig = defineFormConfig([
  ...baseUserForm,
  { type: "input", prop: "password", label: "密码" }, // 编辑时非必填
]);

字典管理

预加载常用字典

typescript
setupPageTemplate({
  dict: {
    preload: true,
    commonTypes: [
      "sys_status",
      "sys_yes_no",
      "sys_user_sex",
      "sys_normal_disable",
    ],
  },
});

自定义适配器命名规范

typescript
const CUSTOM_ADAPTERS = {
  // 业务实体列表:{实体}_list
  user_list: {
    /* ... */
  },
  dept_list: {
    /* ... */
  },

  // 带条件的列表:{实体}_{条件}_list
  user_active_list: {
    /* ... */
  },

  // 特定业务:{业务}_{用途}
  insurance_commissioner: {
    /* ... */
  },
};

表单验证

常用验证规则

typescript
const formConfig = defineFormConfig([
  // 必填
  { type: "input", prop: "name", label: "名称", required: true },

  // 手机号
  {
    type: "input",
    prop: "phone",
    label: "手机号",
    rules: [
      {
        pattern: /^1[3-9]\d{9}$/,
        message: "请输入正确的手机号",
        trigger: "blur",
      },
    ],
  },

  // 邮箱
  {
    type: "input",
    prop: "email",
    label: "邮箱",
    rules: [{ type: "email", message: "请输入正确的邮箱", trigger: "blur" }],
  },

  // 长度限制
  {
    type: "input",
    prop: "code",
    label: "编码",
    rules: [
      { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" },
    ],
  },

  // 数字范围
  {
    type: "number",
    prop: "age",
    label: "年龄",
    min: 0,
    max: 150,
  },
]);

抽取通用验证规则

typescript
// src/utils/rules.ts
export const rules = {
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号", trigger: "blur" },
  ],
  email: [{ type: "email", message: "请输入正确的邮箱", trigger: "blur" }],
  idCard: [
    {
      pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
      message: "请输入正确的身份证号",
      trigger: "blur",
    },
  ],
};

// 使用
{ type: 'input', prop: 'phone', label: '手机号', rules: rules.phone }

权限控制

统一定义权限

typescript
// src/config/permissions.ts
import { definePermissions } from "vue-admin-kit";

export const userPermissions = definePermissions({
  add: ["system:user:add"],
  edit: ["system:user:edit"],
  delete: ["system:user:remove"],
  export: ["system:user:export"],
  import: ["system:user:import"],
});

// 页面中使用
{
  title: '新增',
  hasPermi: userPermissions.add,
  onClick: handleAdd
}

条件显示最佳实践

typescript
import { showWhen, showWhenIn, showAll, showAny } from "vue-admin-kit";

// 简单条件
show: showWhen("status", "1");

// 多值
show: showWhenIn("status", ["1", "2"]);

// 复杂条件抽取为函数
const canEdit = showAll(showWhen("status", "1"), showWhen("isOwner", true));
const canDelete = showAny(showWhen("role", "admin"), showWhen("isOwner", true));

// 使用
{ title: '编辑', show: canEdit, onClick: handleEdit }
{ title: '删除', show: canDelete, onClick: handleDelete }

性能优化

避免不必要的响应式

typescript
// ❌ 不推荐:每次渲染都创建新配置
const columnsConfig = computed(() => [{ field: "name", title: "名称" }]);

// ✅ 推荐:静态配置
const columnsConfig = defineColumnsConfig([{ field: "name", title: "名称" }]);

合理使用字典缓存

typescript
// ❌ 不推荐:频繁清除缓存
onMounted(() => {
  clearDictCache();
  loadData();
});

// ✅ 推荐:只在必要时清除
const handleRefreshDict = () => {
  clearDictCache("sys_status");
};

表格列优化

typescript
// ❌ 不推荐:复杂的 formatter
{
  field: 'amount',
  formatter: ({ row }) => {
    // 复杂计算
    return expensiveCalculation(row);
  }
}

// ✅ 推荐:使用简单的 formatter 或预处理数据
{
  field: 'amount',
  formatter: withUnit('元')
}

代码风格

配置顺序

typescript
useState({
  // 1. API 配置
  api: {
    /* ... */
  },

  // 2. 搜索配置
  searchConfig: [
    /* ... */
  ],

  // 3. 表单配置
  formConfig: [
    /* ... */
  ],

  // 4. 列配置
  columnsConfig: [
    /* ... */
  ],

  // 5. 表格选项
  tableOptions: {
    /* ... */
  },
});

使用 defineXxxConfig

始终使用辅助函数包装配置,获得类型提示:

typescript
// ✅ 推荐
const searchConfig = defineSearchConfig([...]);
const formConfig = defineFormConfig([...]);
const columnsConfig = defineColumnsConfig([...]);
const api = defineApiConfig({...});

// ❌ 不推荐
const searchConfig = [...];

Released under the MIT License.