Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f7ef29a928 | ||
|
|
f7ee862e0f | ||
|
|
8ac1427015 | ||
|
|
ebe5937fb6 | ||
|
|
de18412010 | ||
|
|
2b33bca681 | ||
|
|
ac57de97cb | ||
|
|
0b8f873a4c | ||
|
|
d580fc53b9 | ||
|
|
9746be581d | ||
|
|
f210ce4582 |
@@ -7,8 +7,7 @@ Shrimp 框架前端 —— 一种**经典解决方案**(不是框架本身),消
|
||||
## 安装
|
||||
|
||||
```bash
|
||||
# 推荐 HTTP
|
||||
npm i git+http://git.zeromvc.com/wc24/shrimp-admin.git#v0.1.0
|
||||
npm i git+http://git.zeromvc.com/wc24/shrimp-admin.git#v0.3.0
|
||||
```
|
||||
|
||||
shrimp-admin 是**源码 ship**(.ts + .vue 直接发),由消费侧 Vite 编译。
|
||||
@@ -20,6 +19,8 @@ shrimp-admin 是**源码 ship**(.ts + .vue 直接发),由消费侧 Vite 编译
|
||||
import { createApp } from 'vue'
|
||||
import { createShrimpAdmin, App } from 'shrimp-admin'
|
||||
import 'shrimp-admin/style'
|
||||
import zhCn from './locales/zh-cn.json'
|
||||
import en from './locales/en.json'
|
||||
|
||||
const app = createApp(App)
|
||||
app.use(createShrimpAdmin({
|
||||
@@ -27,22 +28,111 @@ app.use(createShrimpAdmin({
|
||||
API_URL: '/admin-api',
|
||||
TIMEOUT: 10000,
|
||||
},
|
||||
moduleSources: import.meta.glob('./module/**/*.vue'),
|
||||
customFields: import.meta.glob('./module/fields/Field*.vue'),
|
||||
locales: { 'zh-cn': zhCn, en },
|
||||
sources: import.meta.glob('./shrimp/**/*.vue'),
|
||||
}))
|
||||
app.mount('#app')
|
||||
```
|
||||
|
||||
## 唯一约定: `sources` 路径后缀覆盖
|
||||
|
||||
消费侧把所有要交给框架的 .vue 通过单个 `sources` 入口注入(`import.meta.glob` 必须由消费侧自己调用,vite 静态扫描相对调用文件)。框架按**文件路径后缀**匹配,同后缀消费侧优先,内置兜底。
|
||||
|
||||
```
|
||||
项目/
|
||||
└── src/shrimp/ 消费侧目录,可任意命名
|
||||
├── components/
|
||||
│ ├── login.vue 覆盖框架内置 login 页
|
||||
│ ├── layout.vue 覆盖整体布局壳
|
||||
│ └── fields/
|
||||
│ └── FieldRelativeTime.vue 注册字段类型 relativeTime
|
||||
└── module/
|
||||
├── product.vue 业务模块,routed by moduleKey
|
||||
└── user/
|
||||
└── orders.vue 子模块,parent=user
|
||||
```
|
||||
|
||||
### 覆盖颗粒度只在 3 个入口
|
||||
|
||||
框架内 .vue 之间的 peer 引用是**硬编码静态 import**,override 颗粒度就停在下面这 3 类入口,不会一路传递下去:
|
||||
|
||||
| 入口 | 后缀 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| **router targets** | `components/login.vue`、`components/layout.vue`、`components/404.vue` | vue-router 三个根级路由组件 |
|
||||
| **module routes** | `module/<key>.vue`、`module/<parent>/<sub>.vue` | 走 `registerRoute` 的业务模块/子模块 |
|
||||
| **field registry** | `components/fields/Field<X>.vue` | 字段类型注册表(文件名首字母小写 = type 键) |
|
||||
|
||||
想换更细的部件(比如 layout 里的 topbar)就在消费侧的 `layout.vue` 自己组装 — 框架不再代理任何 peer 切换。
|
||||
|
||||
### 字段类型注册
|
||||
|
||||
`components/fields/Field<X>.vue` 自动注册类型 `<x>`(首字母小写):
|
||||
|
||||
| 文件 | type 注册键 |
|
||||
| -------------------------- | ---------------- |
|
||||
| `FieldString.vue` | `string` |
|
||||
| `FieldRelativeTime.vue` | `relativeTime` |
|
||||
| 你自己的 `FieldMyType.vue` | `myType` |
|
||||
|
||||
后端 moduleInfo 里 `field.type === 'myType'` 时就用你这个组件。内置类型: `string` / `boolean` / `date` / `json` / `number` / `password` / `relation` / `select` / `tab` / `textarea` / `relativeTime`。
|
||||
|
||||
### 业务模块
|
||||
|
||||
`module/<key>.vue` 命中 `moduleKey === '<key>'` 的路由,自动作为内容页。子表用嵌套目录(`module/<parent>/<sub>.vue`)。
|
||||
|
||||
### 例子: 覆盖 login 页
|
||||
|
||||
```vue
|
||||
<!-- src/shrimp/components/login.vue -->
|
||||
<template>
|
||||
<div class="custom-login">
|
||||
<h2>{{ vueAdmin.adminConfig.title || 'Admin' }}</h2>
|
||||
<el-form :model="form" :rules="rules" @keyup.enter="login">
|
||||
<el-form-item prop="user">
|
||||
<el-input v-model="form.user" :placeholder="$t('login.userPlaceholder')" />
|
||||
</el-form-item>
|
||||
<el-form-item prop="password">
|
||||
<el-input v-model="form.password" :placeholder="$t('login.PWPlaceholder')" show-password />
|
||||
</el-form-item>
|
||||
<el-button type="primary" :loading="info.islogin" @click="login">
|
||||
{{ $t('login.signIn') }}
|
||||
</el-button>
|
||||
</el-form>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { reactive, computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { vueAdmin } from 'shrimp-admin'
|
||||
|
||||
const { t } = useI18n()
|
||||
const info = reactive({ islogin: false })
|
||||
const form = reactive({ user: '', password: '' })
|
||||
const rules = computed(() => ({
|
||||
user: [{ required: true, message: t('login.userError'), trigger: 'blur' }],
|
||||
password: [{ required: true, message: t('login.PWError'), trigger: 'blur' }],
|
||||
}))
|
||||
|
||||
function login() {
|
||||
info.islogin = true
|
||||
vueAdmin.fetchLogin({ username: form.user, password: form.password })
|
||||
.then(async (data: any) => {
|
||||
vueAdmin.token = data.token
|
||||
await vueAdmin.loadUserInfo()
|
||||
vueAdmin.router.push(vueAdmin.getFirstMenuPath())
|
||||
})
|
||||
.catch((e: any) => console.warn('[Login]', e.message))
|
||||
.finally(() => { info.islogin = false })
|
||||
}
|
||||
</script>
|
||||
```
|
||||
|
||||
只要文件落在 `src/shrimp/components/login.vue`,被 `sources` 的 glob 扫到,框架的 `/login` 路由就会用你这份替换内置版本。
|
||||
|
||||
## 消费的契约
|
||||
|
||||
参见 shrimp-server README `## 约定` 章节。本包消费以下条件契约:
|
||||
|
||||
- **ShrimpTable**: list 响应 `{list,total,page,pageSize,totalPages}` / 字段 type 枚举 / populate `${key}_label`
|
||||
- **ShrimpServer**: HTTP 路由 / JWT Bearer / IUserAccessor 返回的 powers
|
||||
- **默认 Field*.vue**: 字段 type 必须是内置枚举之一,或通过 `customFields` 注册
|
||||
|
||||
## 扩展点
|
||||
|
||||
- `customFields` — 业务字段组件(`Field<Name>.vue`)
|
||||
- `moduleSources` — 业务模块组件(`module/<key>.vue` / `module/<parent>/<sub>.vue`)
|
||||
- `vueAdmin.registerField(type, comp)` / `overrideField(moduleKey, fieldKey, comp)` — 运行时也可
|
||||
|
||||
+1
-4
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "shrimp-admin",
|
||||
"version": "0.1.0",
|
||||
"version": "0.3.3",
|
||||
"private": true,
|
||||
"description": "Shrimp 框架前端 — 消费 ShrimpServer + ShrimpTable 契约的经典 Vue3 + Element Plus 实现",
|
||||
"main": "src/index.ts",
|
||||
@@ -17,9 +17,6 @@
|
||||
"src",
|
||||
"README.md"
|
||||
],
|
||||
"dependencies": {
|
||||
"shrimp-server": "git+http://git.zeromvc.com/wc24/shrimp-server.git#v0.5.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"vue": "^3.3.0",
|
||||
"vue-router": "^4.0.0",
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { computed } from "vue";
|
||||
import { vueAdmin } from "../VueAdmin";
|
||||
import { vueAdmin } from "./VueAdmin";
|
||||
import zhCn from 'element-plus/es/locale/lang/zh-cn'
|
||||
import en from 'element-plus/es/locale/lang/en'
|
||||
|
||||
@@ -20,5 +20,5 @@ const locale = computed(() => {
|
||||
});
|
||||
</script>
|
||||
<style lang="scss">
|
||||
@use "../style/style.scss";
|
||||
@use "./style/style.scss";
|
||||
</style>
|
||||
@@ -0,0 +1,376 @@
|
||||
/**
|
||||
* Shrimp 类型契约 — 前后端 wire protocol 定义(前端副本)
|
||||
*
|
||||
* @syncedFrom shrimp-server contract 1.0.0
|
||||
*
|
||||
* 这是 shrimp-server/src/IShrimpType.ts 的逐字副本。
|
||||
* 不要在这里改 wire protocol,先改 shrimp-server 那份升版本,再 copy 过来更新 @syncedFrom。
|
||||
*
|
||||
* 故意保留副本而不 import 'shrimp-server' 的原因:
|
||||
* - shrimp-server 入口会把 mongoose / express 牵进前端 bundle
|
||||
* - 拆 './types' 子入口会绕开 vite optimize、可读性也差
|
||||
* - 类型契约低频改动,版本号对照即可
|
||||
*/
|
||||
|
||||
/** 业务错误码 */
|
||||
export enum ShrimpCode {
|
||||
OK = 0,
|
||||
FAIL = 1,
|
||||
UNAUTHORIZED = 401,
|
||||
FORBIDDEN = 403,
|
||||
NOT_FOUND = 404,
|
||||
SERVER_ERROR = 500,
|
||||
}
|
||||
|
||||
/** 业务错误 - tip 展示给用户 */
|
||||
export class ShrimpError extends Error {
|
||||
code: ShrimpCode
|
||||
tip: ILabel
|
||||
constructor(tip: ILabel, code: ShrimpCode = ShrimpCode.FAIL) {
|
||||
super(extractILabelText(tip))
|
||||
this.code = code
|
||||
this.tip = tip
|
||||
this.name = 'ShrimpError'
|
||||
}
|
||||
}
|
||||
|
||||
/** 抽取 ILabel 的字符串形态用于 Error.message / 日志(非展示) */
|
||||
function extractILabelText(v: ILabel): string {
|
||||
if (typeof v === 'string') return v
|
||||
if (v && typeof v === 'object') {
|
||||
const o = v as any
|
||||
if ('t' in o) return o.t
|
||||
if ('tc' in o) return o.tc
|
||||
if ('d' in o) return String(o.d)
|
||||
if ('n' in o) return String(o.n)
|
||||
}
|
||||
return '[ILabel]'
|
||||
}
|
||||
|
||||
/** 统一响应格式 */
|
||||
export interface IShrimpResponse<T = any> {
|
||||
code: ShrimpCode
|
||||
data?: T
|
||||
tip?: ILabel // 给用户看的提示
|
||||
log?: string // 给开发者看的日志
|
||||
}
|
||||
|
||||
/** 模块信息(结构元数据,扁平表示:子模块与主模块同列,通过 parent 关联) */
|
||||
export interface IModuleInfo {
|
||||
moduleKey: string
|
||||
events: string[]
|
||||
label: ILabel
|
||||
fields: IFieldConfig[]
|
||||
icon?: string // 子模块跳转按钮图标(element-plus icon 名称)
|
||||
parent?: string // 父模块 moduleKey;存在即为子模块(不进菜单、路径嵌套)
|
||||
}
|
||||
|
||||
/** 登录结果(仅 token) */
|
||||
export interface ILoginResult {
|
||||
token: string
|
||||
}
|
||||
|
||||
/** 当前用户信息 */
|
||||
export interface IMeResult {
|
||||
nickname?: string
|
||||
moduleInfo: IModuleInfo[]
|
||||
menuTree: IMenuItem[]
|
||||
options?: Record<string, any>
|
||||
}
|
||||
|
||||
// ============== 通用类型 ==============
|
||||
|
||||
/**
|
||||
* 通用国际化标签 - 所有前端可见文本字段统一类型
|
||||
*
|
||||
* 形态:
|
||||
* - string 字面量,前端原样显示
|
||||
* - { t: 'i18n.key', params?: ... } 翻译(vue-i18n t)
|
||||
* - { tc: 'i18n.key', count, params?: ... } 复数(vue-i18n tc)
|
||||
* - { d: Date|number, format? } 日期格式化(vue-i18n d)
|
||||
* - { n: number, format? } 数字/货币格式化(vue-i18n n)
|
||||
* - { zh: '提交', en: 'Submit' } 内联多语言
|
||||
*
|
||||
* params 值本身可以是 ILabel,前端递归解析
|
||||
*/
|
||||
export type ILabel =
|
||||
| string
|
||||
| { t: string; params?: Record<string, ILabel | any> }
|
||||
| { tc: string; count: number; params?: Record<string, ILabel | any> }
|
||||
| { d: number | Date; format?: string }
|
||||
| { n: number; format?: string }
|
||||
| Record<string, string>
|
||||
|
||||
/** 菜单项 */
|
||||
export interface IMenuItem {
|
||||
name: string
|
||||
icon?: string
|
||||
label: ILabel // 菜单显示名称
|
||||
path?: string
|
||||
moduleKey?: string
|
||||
children?: IMenuItem[]
|
||||
}
|
||||
|
||||
// ============== Proto 协议定义 ==============
|
||||
|
||||
/** 标准 Table CRUD 协议(前端可见) */
|
||||
export interface ITableProto<T> {
|
||||
list(query?: IPageQuery & any): Promise<IPageResult<T>>
|
||||
get(id: string): Promise<T | null>
|
||||
add(item: Omit<T, '_id'>, ownerId?: string): Promise<T>
|
||||
edit(id: string, item: Partial<T>): Promise<T | null>
|
||||
delete(id: string): Promise<boolean>
|
||||
}
|
||||
|
||||
/** 完整 Table 协议(后端可用,含管理操作) */
|
||||
export interface ITableCrudProto<T> extends ITableProto<T> {
|
||||
clear(query?: IPageQuery & any): Promise<boolean>
|
||||
export(query?: IPageQuery & any): Promise<T[]>
|
||||
import(data?: T[], ownerId?: string): Promise<void>
|
||||
}
|
||||
|
||||
// ============== 预制数据模型 ==============
|
||||
|
||||
/** 用户 */
|
||||
export interface IUser {
|
||||
username: string
|
||||
password: string
|
||||
nickname: string
|
||||
roleId: string[]
|
||||
active: boolean
|
||||
createdAt: number
|
||||
updatedAt: number
|
||||
}
|
||||
|
||||
/** 角色 */
|
||||
export interface IRole {
|
||||
name: string
|
||||
description: string
|
||||
isSuperAdmin: boolean
|
||||
powers: string[]
|
||||
createdAt: number
|
||||
updatedAt: number
|
||||
}
|
||||
|
||||
/** 操作日志 */
|
||||
export interface IOperationLog {
|
||||
operatorId: string | null // 操作者 userId,登录失败等场景为 null
|
||||
ip: string // 来源 IP
|
||||
method: string // RPC 路径,如 "user.edit"、"login"
|
||||
args: string // 参数(已脱敏 + JSON.stringify + 截断)
|
||||
success: boolean
|
||||
errorMsg: string // success=false 时填错误信息
|
||||
createdAt: number
|
||||
}
|
||||
|
||||
/** 为数据模型注入 _id 的泛型工具类型 */
|
||||
export type WithId<T> = T & { _id: string }
|
||||
|
||||
/** 操作者契约 - 框架层通用操作者上下文,不依赖具体用户模型 */
|
||||
export interface IShrimpOperator {
|
||||
userId: string
|
||||
roleId: string[]
|
||||
isSuperAdmin: boolean
|
||||
}
|
||||
|
||||
/** 权限 */
|
||||
export interface IShrimpPowerData {
|
||||
_id: string
|
||||
powerKey: string
|
||||
}
|
||||
|
||||
// ============== 前端客户端接口 ==============
|
||||
|
||||
/** 底层请求函数类型 */
|
||||
export type ShrimpRequestFn = (path: string[], ...args: any[]) => Promise<IShrimpResponse>
|
||||
|
||||
/** Shrimp 客户端接口(前端实现) */
|
||||
export interface IShrimpClient {
|
||||
shrimpRequest: ShrimpRequestFn
|
||||
hasEvent(moduleKey: string, eventName: string): boolean
|
||||
}
|
||||
|
||||
// ============== 字段配置 ==============
|
||||
//
|
||||
// 【功能说明 - 给前端】
|
||||
//
|
||||
// IFieldConfig 是 Shrimp 框架的动态字段配置系统。
|
||||
// 后端模块定义 fields 后,前端通过 GET /me 获取 moduleInfo[].fields,
|
||||
// 即可自动生成表格列、搜索栏、新增/编辑表单,无需硬编码页面结构。
|
||||
//
|
||||
// 注意: _id 由框架自动注入(tableHide=true), 不需要在 fields 中配置, 数据返回但表格不显示。
|
||||
//
|
||||
// 使用流程:
|
||||
// 1. 调用 GET /me → 拿到 moduleInfo 数组
|
||||
// 2. 每个 moduleInfo 包含: moduleKey(模块名), events(可调用接口), fields(字段配置)
|
||||
// 3. 根据 fields 渲染:
|
||||
// - 表格列: 非 hidden 且非 tableHide 的字段 → 列标题=label, 数据=key
|
||||
// - 搜索栏: searchable=true 的字段 → 渲染对应类型的搜索输入
|
||||
// - 表单: 非 hidden 且 editable≠"readonly" 的字段, 根据 editable 决定:
|
||||
// editable="always" 或缺省 → 新增/编辑都可编辑
|
||||
// editable="readonly" → 新增/编辑都不可编辑(只读,如createdAt)
|
||||
// editable="addOnly" → 新增可编辑, 编辑时不可编辑(如username)
|
||||
// required=true 的字段标记必填, defaultValue 填入默认值
|
||||
// - 排序: sortable=true 的字段 → 表头可点击排序
|
||||
//
|
||||
// type 与前端控件映射建议:
|
||||
// string → Input 文本框
|
||||
// number → InputNumber 数字框
|
||||
// boolean → Switch 开关
|
||||
// date → DatePicker 日期选择器
|
||||
// select → Select 下拉框, 选项由 options 提供
|
||||
// textarea → Input.TextArea 多行文本
|
||||
// password → Input.Password 密码框
|
||||
// relation → Select 下拉框, 选项从 moduleKey 指定的模块 list 接口获取,
|
||||
// 显示字段为 labelKey, 值为 _id
|
||||
//
|
||||
|
||||
/** 字段类型(string 基础类型,前端可自由扩展自定义类型) */
|
||||
export type ShrimpFieldType = string
|
||||
|
||||
/** 框架内置字段类型常量(前端可直接使用或在此基础上扩展) */
|
||||
export const ShrimpFieldTypes = {
|
||||
String: "string" as ShrimpFieldType,
|
||||
Number: "number" as ShrimpFieldType,
|
||||
Boolean: "boolean" as ShrimpFieldType,
|
||||
Date: "date" as ShrimpFieldType,
|
||||
Select: "select" as ShrimpFieldType,
|
||||
Textarea: "textarea" as ShrimpFieldType,
|
||||
Password: "password" as ShrimpFieldType,
|
||||
Relation: "relation" as ShrimpFieldType,
|
||||
Json: "json" as ShrimpFieldType,
|
||||
Tab: "tab" as ShrimpFieldType,
|
||||
}
|
||||
|
||||
/** 字段可编辑状态 */
|
||||
export type FieldEditable = "always" | "readonly" | "addOnly"
|
||||
|
||||
/** 字段类型处理器:定义每种 type 在请求/响应时的转换、验证、默认值 */
|
||||
export interface IFieldTypeHandler {
|
||||
/** 请求过滤:前端提交 → 保存前转换(如密码哈希、trim) */
|
||||
reqFilter?: (value: any, field: IFieldConfig, item: Record<string, any>) => any | Promise<any>
|
||||
/** 响应过滤:数据库取出 → 返回前端前转换(如密码脱敏为 ***、日期格式化) */
|
||||
resFilter?: (value: any, field: IFieldConfig, item: Record<string, any>) => any
|
||||
/** 验证:保存前校验,返回错误 ILabel 或 null(可直接返回字面字符串、{t}、{tc} 等) */
|
||||
validate?: (value: any, field: IFieldConfig, item: Record<string, any>) => ILabel | null | Promise<ILabel | null>
|
||||
/** 新增时的默认值(静态值或工厂函数) */
|
||||
defaultValue?: any | (() => any)
|
||||
}
|
||||
|
||||
/** 字段配置 */
|
||||
export interface IFieldConfig {
|
||||
key: string // 字段名(对应数据对象的属性名)
|
||||
label: ILabel // 显示名称(表格列标题、表单标签)
|
||||
type: ShrimpFieldType // 字段类型(决定前端渲染哪种控件)
|
||||
required?: boolean // 是否必填(表单校验)
|
||||
hidden?: boolean // 数据不返回给前端
|
||||
tableHide?: boolean // 表格中不显示此列,但数据仍返回(如 _id)
|
||||
editable?: FieldEditable // 可编辑状态: always(默认,始终可编辑) | readonly(始终只读,如createdAt) | addOnly(仅添加可编辑,编辑时只读,如username)
|
||||
searchable?: boolean // 是否可搜索(出现在搜索栏)
|
||||
sortable?: boolean // 是否可排序(表头可点击排序)
|
||||
filterable?: boolean // 是否可筛选(出现在筛选栏,用于 filter 精确匹配)
|
||||
options?: { label: ILabel; value: any }[] | string // select 类型的可选项,或全局 options key
|
||||
relation?: { // relation 类型的关联配置
|
||||
moduleKey: string // 关联模块名(从该模块的 list 接口获取选项)
|
||||
labelKey: string // 关联模块中用作显示的字段名
|
||||
}
|
||||
defaultValue?: any // 新增时的默认值(优先级高于 typeHandler.defaultValue)
|
||||
multiple?: boolean // 是否支持多选(relation、select 等)
|
||||
rules?: IFieldRule[] // 通用验证规则(前后端共用)
|
||||
/** tab 类型专用:每个 type 对应的子字段配置 */
|
||||
tabs?: { key: any; label: ILabel; fields: IFieldConfig[] }[]
|
||||
}
|
||||
|
||||
/** 通用验证规则(前后端共用) */
|
||||
export interface IFieldRule {
|
||||
required?: boolean
|
||||
min?: number
|
||||
max?: number
|
||||
pattern?: string
|
||||
message?: ILabel
|
||||
}
|
||||
|
||||
// ============== 预制协议 ==============
|
||||
|
||||
/** 分页查询参数 */
|
||||
export interface IPageQuery {
|
||||
page?: number // 页码,从 1 开始
|
||||
pageSize?: number // 每页数量,默认 ShrimpConfig.defaultPageSize
|
||||
keyword?: string // 关键词搜索,按 searchable 字段模糊匹配
|
||||
sortBy?: string // 排序字段(对应 field.key)
|
||||
sortOrder?: 'asc' | 'desc' // 排序方向
|
||||
filter?: Record<string, any> // 字段精确匹配条件(AND 关系)
|
||||
ownerId?: string // 子表场景: 父记录 _id。后端按模块 ownerKey 配置翻译为 filter 注入(用户无法绕过)
|
||||
}
|
||||
|
||||
/** Shrimp 全局配置 */
|
||||
export class ShrimpConfig {
|
||||
static defaultPageSize: number = 100000
|
||||
}
|
||||
|
||||
/** 分页结果 */
|
||||
export interface IPageResult<T> {
|
||||
list: T[] // 当前页数据
|
||||
total: number // 总记录数
|
||||
page: number // 当前页码
|
||||
pageSize: number // 每页数量
|
||||
totalPages: number // 总页数
|
||||
}
|
||||
|
||||
// ============== 数据源查询协议 ==============
|
||||
//
|
||||
// IShrimpQuery 是数据源无关的查询协议。
|
||||
// ShrimpTableModule 负责将前端参数(IPageQuery)翻译为 IShrimpQuery,
|
||||
// 各 ShrimpCrud 实现(MemoryCrud/MongoShrimpCrud)负责执行。
|
||||
//
|
||||
// 查询语义:
|
||||
// WHERE (where 全部满足) AND (orWhere 至少一组满足)
|
||||
// ORDER BY order
|
||||
// LIMIT limit OFFSET offset
|
||||
//
|
||||
|
||||
/** 查询条件运算符 */
|
||||
export interface IShrimpCondition {
|
||||
eq?: any // 精确匹配 (=)
|
||||
in?: any[] // IN 查询
|
||||
like?: string // 模糊匹配 (不区分大小写)
|
||||
gte?: any // 大于等于 (>=)
|
||||
lte?: any // 小于等于 (<=)
|
||||
}
|
||||
|
||||
/** 判断值是否为 IShrimpCondition 对象 */
|
||||
export function isShrimpCondition(val: any): val is IShrimpCondition {
|
||||
return val != null && typeof val === 'object' && !Array.isArray(val)
|
||||
&& ('eq' in val || 'in' in val || 'like' in val || 'gte' in val || 'lte' in val)
|
||||
}
|
||||
|
||||
/** 关联填充指令 */
|
||||
export interface IShrimpPopulate {
|
||||
key: string // 当前模块的字段名 (如 roleId)
|
||||
moduleKey: string // 关联模块名 (如 role)
|
||||
labelKey: string // 关联模块中用作显示的字段 (如 name)
|
||||
}
|
||||
|
||||
/** 通用查询协议 (数据源无关) */
|
||||
export interface IShrimpQuery {
|
||||
where?: Record<string, IShrimpCondition | any> // AND 条件 (原始值=eq简写)
|
||||
orWhere?: Record<string, IShrimpCondition>[] // OR 条件组 (用于 keyword)
|
||||
order?: [string, 'asc' | 'desc'][] // 排序
|
||||
offset?: number // 偏移量
|
||||
limit?: number // 限制数量
|
||||
populate?: IShrimpPopulate[] // 关联填充 (输出 {key}_label)
|
||||
}
|
||||
|
||||
/** 权限项 */
|
||||
export interface IPowerItem {
|
||||
key: string
|
||||
label: ILabel
|
||||
}
|
||||
|
||||
/** 用户模块协议 */
|
||||
export interface IUserProto extends ITableCrudProto<WithId<IUser>> { }
|
||||
|
||||
/** 角色模块协议 */
|
||||
export interface IRoleProto extends ITableCrudProto<WithId<IRole>> {
|
||||
allPower(): Promise<IPowerItem[]>
|
||||
}
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
* ShrimpClient — Shrimp 框架前端基类
|
||||
* 框架无关层,包含协议通信、模块管理、菜单树操作
|
||||
*/
|
||||
import { ShrimpCode, ShrimpRequestFn, IShrimpResponse, IModuleInfo, IMenuItem, ILoginResult, IMeResult, IShrimpClient, ILabel } from 'shrimp-server/types'
|
||||
import { ShrimpCode, ShrimpRequestFn, IShrimpResponse, IModuleInfo, IMenuItem, ILoginResult, IMeResult, IShrimpClient, ILabel } from './IShrimpType'
|
||||
|
||||
/** tip 展示接口(由框架层实现,如 Element Plus)。msg 是 ILabel,实现层负责翻译后展示 */
|
||||
export interface IShrimpTipper {
|
||||
|
||||
+94
-69
@@ -7,10 +7,25 @@ import { createRouter, createWebHashHistory, Router } from 'vue-router'
|
||||
import zh_cn from './locales/zh-cn.json'
|
||||
import en from './locales/en.json'
|
||||
import { createI18n, I18n } from 'vue-i18n'
|
||||
import { IShrimpResponse, ILabel } from 'shrimp-server/types'
|
||||
import { IShrimpResponse, ILabel } from './IShrimpType'
|
||||
|
||||
import { ShrimpClient, handleShrimpResponse, type IShrimpTipper, type IRouteInfo } from './ShrimpClient'
|
||||
import FieldString from './components/fields/FieldString.vue'
|
||||
|
||||
// ============== 工具 ==============
|
||||
|
||||
/** locale 深合并:嵌套对象按 key 递归 merge,非对象值 src 覆盖 dst。仅服务于 i18n messages,没必要拉 lodash。 */
|
||||
function deepMerge(dst: Record<string, any>, src: Record<string, any>): Record<string, any> {
|
||||
const out: Record<string, any> = { ...dst }
|
||||
for (const key in src) {
|
||||
const sv = src[key], dv = out[key]
|
||||
if (sv && typeof sv === 'object' && !Array.isArray(sv) && dv && typeof dv === 'object' && !Array.isArray(dv)) {
|
||||
out[key] = deepMerge(dv, sv)
|
||||
} else {
|
||||
out[key] = sv
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// ============== Options ==============
|
||||
|
||||
@@ -23,50 +38,65 @@ export interface ShrimpAdminConfig {
|
||||
LS_ENCRYPTION_key?: string
|
||||
}
|
||||
|
||||
type VueLoader = () => Promise<any>
|
||||
|
||||
export interface ShrimpAdminOptions {
|
||||
config: ShrimpAdminConfig
|
||||
/** 业务模块组件:`import.meta.glob('./module/**\/*.vue')` 的结果 */
|
||||
moduleSources?: Record<string, () => Promise<{ default: Component } | Component>>
|
||||
/** 业务字段组件:`import.meta.glob('./module/fields/Field*.vue')`,文件名 FieldXxx → type='fieldXxx' */
|
||||
customFields?: Record<string, () => Promise<{ default: Component } | Component>>
|
||||
/**
|
||||
* 消费侧 .vue 源,推荐 `import.meta.glob('./shrimp/**\/*.vue')`。
|
||||
* - `shrimp/components/<name>.vue` 同后缀覆盖框架内置(login/layout/topbar/ShrimpTable/...)
|
||||
* - `shrimp/components/fields/Field<X>.vue` 注册字段类型 `<x>`(首字母小写),同名覆盖内置
|
||||
* - `shrimp/module/<key>.vue` 业务模块组件(routed by moduleKey)
|
||||
*/
|
||||
sources?: Record<string, VueLoader>
|
||||
/** 语言资源,与框架自带的合并(消费侧同 key 覆盖框架默认) */
|
||||
locales?: Record<string, any>
|
||||
/** 语言列表,默认 [{ lang: 'zh-cn', name: '简体中文' }] */
|
||||
langList?: { lang: string; name: string }[]
|
||||
}
|
||||
|
||||
// ============== 源注册表 ==============
|
||||
//
|
||||
// 框架在 3 个入口点用消费侧 sources 覆盖内置(按路径后缀同后缀覆盖):
|
||||
// 1. router: components/{layout,login,404}.vue
|
||||
// 2. registerRoute: module/<key>.vue 等业务模块
|
||||
// 3. fieldRegistry: components/fields/Field<X>.vue (按文件名导出的字段类型)
|
||||
// 框架内 .vue 之间的 peer 引用是硬编码静态 import,override 颗粒度就停在上面这些"入口"。
|
||||
|
||||
const internalSources = import.meta.glob<Component>('./{components,module}/**/*.vue')
|
||||
const externalSources: Record<string, VueLoader> = {}
|
||||
|
||||
/**
|
||||
* 路径后缀匹配解析: 消费侧优先,内置兜底。
|
||||
* suffix 形如 `components/login.vue` / `module/user.vue` / `module/user/operationLog.vue`。
|
||||
*/
|
||||
export function resolveVue(suffix: string): VueLoader {
|
||||
const tail = '/' + suffix
|
||||
for (const key in externalSources) {
|
||||
if (key.endsWith(tail)) return externalSources[key]
|
||||
}
|
||||
for (const key in internalSources) {
|
||||
if (key.endsWith(tail)) return internalSources[key] as any
|
||||
}
|
||||
throw new Error(`[shrimp-admin] resolveVue: ${suffix} not found in sources`)
|
||||
}
|
||||
|
||||
// ============== 字段组件注册表 ==============
|
||||
//
|
||||
// 约定:`components/fields/Field<X>.vue` → 字段类型 `<x>`(首字母小写)。
|
||||
// 后端 moduleInfo 的 field.type 命中这里的 key 就用对应组件,否则回退到 string。
|
||||
|
||||
const fieldRegistry = new Map<string, Component>()
|
||||
const fieldOverrides = new Map<string, string>()
|
||||
|
||||
fieldRegistry.set('string', FieldString)
|
||||
fieldRegistry.set('boolean', defineAsyncComponent(() => import('./components/fields/FieldBoolean.vue')))
|
||||
fieldRegistry.set('date', defineAsyncComponent(() => import('./components/fields/FieldDate.vue')))
|
||||
fieldRegistry.set('number', defineAsyncComponent(() => import('./components/fields/FieldNumber.vue')))
|
||||
fieldRegistry.set('password', defineAsyncComponent(() => import('./components/fields/FieldPassword.vue')))
|
||||
fieldRegistry.set('relation', defineAsyncComponent(() => import('./components/fields/FieldRelation.vue')))
|
||||
fieldRegistry.set('select', defineAsyncComponent(() => import('./components/fields/FieldSelect.vue')))
|
||||
fieldRegistry.set('textarea', defineAsyncComponent(() => import('./components/fields/FieldTextarea.vue')))
|
||||
fieldRegistry.set('json', defineAsyncComponent(() => import('./components/fields/FieldJson.vue')))
|
||||
fieldRegistry.set('tab', defineAsyncComponent(() => import('./components/fields/FieldTab.vue')))
|
||||
function deriveFieldType(path: string): string | null {
|
||||
const m = path.match(/\/components\/fields\/Field([A-Z][A-Za-z0-9]*)\.vue$/)
|
||||
if (!m) return null
|
||||
return m[1][0].toLowerCase() + m[1].slice(1)
|
||||
}
|
||||
|
||||
// 框架自带模块组件 — vite glob 相对本文件解析,扫到的是 shrimp-admin 内部的 module/
|
||||
const internalModules = import.meta.glob<Component>('./module/**/*.vue')
|
||||
|
||||
// 业务模块由消费侧通过 createShrimpAdmin({ moduleSources }) 注册
|
||||
const externalModules: Record<string, () => Promise<any>> = {}
|
||||
|
||||
function resolveModuleComponent(componentPath: string): (() => Promise<any>) | null {
|
||||
const suffix = `/module/${componentPath}.vue`
|
||||
// 业务优先(允许覆盖同名内置)
|
||||
for (const key in externalModules) {
|
||||
if (key.endsWith(suffix)) return externalModules[key]
|
||||
}
|
||||
for (const key in internalModules) {
|
||||
if (key.endsWith(suffix)) return internalModules[key] as any
|
||||
}
|
||||
return null
|
||||
for (const path in internalSources) {
|
||||
const type = deriveFieldType(path)
|
||||
if (type) fieldRegistry.set(type, defineAsyncComponent(internalSources[path] as any))
|
||||
}
|
||||
|
||||
// ============== LocalData ==============
|
||||
@@ -93,21 +123,17 @@ export class VueAdmin extends ShrimpClient {
|
||||
userName = ''
|
||||
config: ShrimpAdminConfig
|
||||
langList: { lang: string; name: string }[]
|
||||
/** 已注册成功的模块路由(moduleKey → IRouteInfo),供 relation 跳转/单项查看解析路由 */
|
||||
moduleRoutes = new Map<string, IRouteInfo>()
|
||||
|
||||
registerField(type: string, comp: Component) { fieldRegistry.set(type, comp) }
|
||||
|
||||
overrideField(moduleKey: string, fieldKey: string, comp: Component) {
|
||||
const registryKey = `__override_${moduleKey}_${fieldKey}`
|
||||
fieldRegistry.set(registryKey, comp)
|
||||
fieldOverrides.set(`${moduleKey}.${fieldKey}`, registryKey)
|
||||
getFieldComponent(_moduleKey: string, type: string, _fieldKey?: string): Component {
|
||||
return fieldRegistry.get(type) || fieldRegistry.get('string')!
|
||||
}
|
||||
|
||||
getFieldComponent(moduleKey: string, type: string, fieldKey?: string): Component {
|
||||
if (fieldKey) {
|
||||
const override = fieldOverrides.get(`${moduleKey}.${fieldKey}`)
|
||||
if (override && fieldRegistry.has(override)) return fieldRegistry.get(override)!
|
||||
}
|
||||
return fieldRegistry.get(type) || FieldString
|
||||
/** 目标模块能否作为「单项查看」跳转目标:已按权限注册路由 且 非子模块。返回其路由信息或 undefined(不可跳) */
|
||||
routeForModule(moduleKey: string): IRouteInfo | undefined {
|
||||
if (this.moduleInfo.find(m => m.moduleKey === moduleKey)?.parent) return undefined
|
||||
return this.moduleRoutes.get(moduleKey)
|
||||
}
|
||||
|
||||
state = reactive({ isMobile: false })
|
||||
@@ -145,15 +171,11 @@ export class VueAdmin extends ShrimpClient {
|
||||
this.config = opts.config
|
||||
this.langList = opts.langList || [{ lang: 'zh-cn', name: '简体中文' }]
|
||||
|
||||
// 业务模块/字段注册
|
||||
if (opts.moduleSources) Object.assign(externalModules, opts.moduleSources)
|
||||
if (opts.customFields) {
|
||||
for (const path in opts.customFields) {
|
||||
const match = path.match(/\/Field(.+)\.vue$/)
|
||||
if (match) {
|
||||
const name = 'field' + match[1]
|
||||
fieldRegistry.set(name, defineAsyncComponent(opts.customFields[path] as any))
|
||||
}
|
||||
if (opts.sources) {
|
||||
Object.assign(externalSources, opts.sources)
|
||||
for (const path in opts.sources) {
|
||||
const type = deriveFieldType(path)
|
||||
if (type) fieldRegistry.set(type, defineAsyncComponent(opts.sources[path] as any))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -169,14 +191,14 @@ export class VueAdmin extends ShrimpClient {
|
||||
}
|
||||
|
||||
initI18n(extraLocales?: Record<string, any>) {
|
||||
const merged: Record<string, any> = {
|
||||
'zh-cn': { ...zh_cn, ...(extraLocales?.['zh-cn'] || {}) },
|
||||
'en': { ...en, ...(extraLocales?.['en'] || {}) },
|
||||
}
|
||||
if (extraLocales) {
|
||||
for (const key in extraLocales) {
|
||||
if (!(key in merged)) merged[key] = extraLocales[key]
|
||||
}
|
||||
// 深合并:框架自带 locale 在底,业务侧叠在上。
|
||||
// 旧版用 spread 浅合并,业务侧只要定义了同名一级键(如 user)就会把框架的 user.* 全部替换,
|
||||
// 表现是控制台 [intlify] Not found 'user.operationLog' key 之类的报错。
|
||||
const builtins: Record<string, any> = { 'zh-cn': zh_cn, 'en': en }
|
||||
const merged: Record<string, any> = {}
|
||||
const langs = new Set([...Object.keys(builtins), ...Object.keys(extraLocales || {})])
|
||||
for (const lang of langs) {
|
||||
merged[lang] = deepMerge(builtins[lang] || {}, extraLocales?.[lang] || {})
|
||||
}
|
||||
this.i18n = createI18n({
|
||||
locale: this.localData.get("lang") || 'zh-cn',
|
||||
@@ -228,8 +250,10 @@ export class VueAdmin extends ShrimpClient {
|
||||
|
||||
registerRoute(info: IRouteInfo) {
|
||||
const componentPath = info.componentPath || info.moduleKey
|
||||
const importer = resolveModuleComponent(componentPath)
|
||||
if (!importer) {
|
||||
let importer: VueLoader
|
||||
try {
|
||||
importer = resolveVue(`module/${componentPath}.vue`)
|
||||
} catch {
|
||||
console.warn(`[shrimp-admin] module component not found: module/${componentPath}.vue`)
|
||||
return
|
||||
}
|
||||
@@ -240,6 +264,7 @@ export class VueAdmin extends ShrimpClient {
|
||||
props: { moduleKey: info.moduleKey, events: info.events },
|
||||
meta: { title: info.label }
|
||||
})
|
||||
this.moduleRoutes.set(info.moduleKey, info)
|
||||
}
|
||||
|
||||
initRouter() {
|
||||
@@ -249,17 +274,17 @@ export class VueAdmin extends ShrimpClient {
|
||||
{
|
||||
name: "layout",
|
||||
path: "/",
|
||||
component: () => import('./views/layout.vue'),
|
||||
component: resolveVue('components/layout.vue'),
|
||||
children: []
|
||||
},
|
||||
{
|
||||
path: "/login",
|
||||
component: () => import('./views/login.vue'),
|
||||
meta: { title: "t:login.signIn" }
|
||||
component: resolveVue('components/login.vue'),
|
||||
meta: { title: { t: 'login.signIn' } }
|
||||
},
|
||||
{
|
||||
path: "/:pathMatch(.*)",
|
||||
component: () => import('./views/404.vue'),
|
||||
component: resolveVue('components/404.vue'),
|
||||
},
|
||||
],
|
||||
})
|
||||
@@ -327,7 +352,7 @@ export class VueAdmin extends ShrimpClient {
|
||||
}
|
||||
},
|
||||
(error) => {
|
||||
ElMessage.error(this.t('t:base.netError'))
|
||||
ElMessage.error(this.t({ t: 'base.netError' }))
|
||||
throw error
|
||||
}
|
||||
)
|
||||
|
||||
@@ -22,7 +22,7 @@
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { provide, computed, ref } from 'vue'
|
||||
import { IFieldConfig, IFieldRule } from 'shrimp-server/types'
|
||||
import { IFieldConfig, IFieldRule } from '../IShrimpType'
|
||||
import { vueAdmin } from '../VueAdmin'
|
||||
import type { FormInstance, FormItemRule } from 'element-plus'
|
||||
|
||||
@@ -53,7 +53,7 @@ function buildRules(field: IFieldConfig): FormItemRule[] {
|
||||
if (field.required) {
|
||||
rules.push({
|
||||
required: true,
|
||||
message: vueAdmin.t('shrimp.fieldRequired'),
|
||||
message: vueAdmin.t({ t: 'shrimp.fieldRequired', params: { field: field.label } }),
|
||||
trigger: 'change',
|
||||
...(field.type === 'string' || field.type === 'textarea' || field.type === 'password' ? { trigger: 'blur' } : {}),
|
||||
})
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { ref, watch } from 'vue'
|
||||
import { IFieldConfig } from 'shrimp-server/types'
|
||||
import { IFieldConfig } from '../IShrimpType'
|
||||
import { vueAdmin } from '../VueAdmin'
|
||||
|
||||
interface Props {
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
<script lang="ts" setup>
|
||||
import { ref, computed, watch, nextTick } from 'vue'
|
||||
import { vueAdmin } from '../VueAdmin'
|
||||
import type { IMenuItem, ILabel } from 'shrimp-server/types'
|
||||
import type { IMenuItem, ILabel } from '../IShrimpType'
|
||||
|
||||
interface IPowerItem {
|
||||
key: string
|
||||
@@ -29,7 +29,7 @@
|
||||
<slot :name="`column-${field.key}`" :row="row" :field="field">
|
||||
<component :is="vueAdmin.getFieldComponent(moduleKey, field.type, field.key)" :field="field"
|
||||
:model-value="row[field.key]" mode="display"
|
||||
v-bind="field.type === 'relation' || field.type === 'textarea' ? { displayLabel: row[field.key + '_label'] } : {}" />
|
||||
v-bind="field.type === 'textarea' || field.type === 'tab' ? { displayLabel: row[field.key + '_label'] } : {}" />
|
||||
</slot>
|
||||
</template>
|
||||
</el-table-column>
|
||||
@@ -78,8 +78,8 @@
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { ref, computed, useSlots, onMounted, type Component } from 'vue'
|
||||
import { ITableCrudProto, IFieldConfig, IModuleInfo, IPageQuery } from 'shrimp-server/types'
|
||||
import { ref, computed, useSlots, onMounted, provide, type Component } from 'vue'
|
||||
import { ITableCrudProto, IFieldConfig, IModuleInfo, IPageQuery } from '../IShrimpType'
|
||||
import { vueAdmin } from '../VueAdmin'
|
||||
import { Plus, Delete as DeleteIcon, Download, Upload, Edit, VideoPlay, VideoPause, Operation } from '@element-plus/icons-vue'
|
||||
import * as ElIcons from '@element-plus/icons-vue'
|
||||
@@ -214,6 +214,9 @@ const filterSlotNames = computed(() => Object.keys(slots).filter(name => name.st
|
||||
const data = ref<any[]>([])
|
||||
const loading = ref(false)
|
||||
const total = ref(0)
|
||||
// relation 显示名字典 { moduleKey: { id: 名 } },由 list 响应带回,provide 给表格里的字段组件查名
|
||||
const refs = ref<Record<string, Record<string, any>>>({})
|
||||
provide('shrimpRefs', refs)
|
||||
|
||||
// ---- 对话框状态 ----
|
||||
|
||||
@@ -501,6 +504,7 @@ async function refresh(query?: Record<string, any>) {
|
||||
Object.assign(pageQuery, query)
|
||||
const res = await api.list(pageQuery)
|
||||
data.value = res.list || []
|
||||
refs.value = res.refs || {}
|
||||
total.value = res.total
|
||||
currentPage.value = res.page
|
||||
currentPageSize.value = res.pageSize
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
<template>
|
||||
<template v-if="mode === 'display'">
|
||||
<template v-if="field.multiple && Array.isArray(displayLabel)">{{ displayLabel.filter(Boolean).join(', ') || '-' }}</template>
|
||||
<template v-else>{{ displayLabel || modelValue || '-' }}</template>
|
||||
<template v-if="field.multiple">
|
||||
<span v-if="!displayItems.length">-</span>
|
||||
<template v-for="(it, i) in displayItems" :key="i"><a v-if="jumpable" class="rel-link" @click.stop="goto(it.id)">{{ it.name }}</a><span v-else>{{ it.name }}</span><span v-if="i < displayItems.length - 1">、</span></template>
|
||||
</template>
|
||||
<template v-else>
|
||||
<a v-if="jumpable && modelValue != null" class="rel-link" @click.stop="goto(modelValue)">{{ displayName }}</a>
|
||||
<span v-else>{{ displayName || '-' }}</span>
|
||||
</template>
|
||||
</template>
|
||||
<el-select
|
||||
v-else-if="mode === 'filter'"
|
||||
@@ -18,16 +24,15 @@
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { ref, onMounted, computed } from 'vue'
|
||||
import { ref, inject, onMounted, computed, type Ref } from 'vue'
|
||||
import { vueAdmin } from '../../VueAdmin'
|
||||
import { ITableCrudProto } from 'shrimp-server/types'
|
||||
import { ITableCrudProto } from '../../IShrimpType'
|
||||
|
||||
const props = defineProps<{
|
||||
field: any
|
||||
modelValue: any
|
||||
mode: 'display' | 'edit' | 'filter'
|
||||
disabled?: boolean
|
||||
displayLabel?: string | string[]
|
||||
}>()
|
||||
|
||||
defineEmits<{
|
||||
@@ -37,6 +42,30 @@ defineEmits<{
|
||||
const options = ref<{ label: string; value: string }[]>([])
|
||||
const loading = ref(false)
|
||||
|
||||
// 显示用:从 ShrimpTable provide 的 refs 字典按 id 查名(替代旧的 _label)
|
||||
const refs = inject<Ref<Record<string, Record<string, any>>>>('shrimpRefs', ref<Record<string, Record<string, any>>>({}))
|
||||
const dict = computed(() => refs.value?.[props.field.relation?.moduleKey] ?? {})
|
||||
const displayName = computed(() => {
|
||||
const id = props.modelValue
|
||||
if (id == null) return ''
|
||||
return dict.value[String(id)] ?? String(id)
|
||||
})
|
||||
const displayItems = computed(() =>
|
||||
(Array.isArray(props.modelValue) ? props.modelValue : [])
|
||||
.filter((id: any) => id != null)
|
||||
.map((id: any) => ({ id, name: dict.value[String(id)] ?? String(id) }))
|
||||
)
|
||||
|
||||
// 单项查看跳转:目标模块可达(已注册路由)且非子模块时,名字可点 → 跳目标模块并过滤到该 _id(单行)
|
||||
const jumpable = computed(() =>
|
||||
props.mode === 'display' && !!props.field.relation && !!vueAdmin.routeForModule(props.field.relation.moduleKey)
|
||||
)
|
||||
function goto(id: any) {
|
||||
const r = props.field.relation && vueAdmin.routeForModule(props.field.relation.moduleKey)
|
||||
if (!r || id == null) return
|
||||
vueAdmin.router.push({ name: r.name, query: { filter: JSON.stringify({ _id: String(id) }) } })
|
||||
}
|
||||
|
||||
/** 统一转为字符串值,解决 ObjectId 与 el-select 的匹配问题 */
|
||||
const stringValue = computed(() => {
|
||||
// filter 模式强制 multiple,始终返回数组
|
||||
@@ -92,3 +121,13 @@ onMounted(async () => {
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.rel-link {
|
||||
color: var(--el-color-primary);
|
||||
cursor: pointer;
|
||||
}
|
||||
.rel-link:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
<script lang="ts" setup>
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { vueAdmin } from '../VueAdmin'
|
||||
import { vueAdmin } from '../../VueAdmin'
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
<template>
|
||||
<template v-if="mode === 'display'">
|
||||
<span v-if="!modelValue || typeof modelValue !== 'object'">-</span>
|
||||
<!-- 表格列展示后端算好的 stringify 文本(displayLabel=${key}_label);本体仍是对象,供编辑/逻辑用 -->
|
||||
<el-tooltip v-if="displayLabel" :content="String(displayLabel)" placement="top">
|
||||
<span class="tab-display">{{ displayLabel }}</span>
|
||||
</el-tooltip>
|
||||
<span v-else-if="!modelValue || typeof modelValue !== 'object'">-</span>
|
||||
<el-tooltip v-else :content="JSON.stringify(modelValue, null, 2)" placement="top">
|
||||
<span class="tab-display">{{ displayText }}</span>
|
||||
</el-tooltip>
|
||||
@@ -35,6 +39,7 @@ const props = defineProps<{
|
||||
modelValue: any
|
||||
mode: 'display' | 'edit' | 'filter'
|
||||
disabled?: boolean
|
||||
displayLabel?: string
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
|
||||
@@ -43,13 +43,13 @@
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import SideM from "./sideM.vue";
|
||||
import { ref, watch } from "vue";
|
||||
import { vueAdmin } from "../VueAdmin";
|
||||
import { type IMenuItem } from "../IShrimpType";
|
||||
import SideM from "./sideM.vue";
|
||||
import navMenu from "./navMenu.vue";
|
||||
import Topbar from "./topbar.vue";
|
||||
import Userbar from "./userbar.vue";
|
||||
import { vueAdmin } from "../VueAdmin";
|
||||
import { type IMenuItem } from "shrimp-server/types";
|
||||
import Logo from "./logo.vue";
|
||||
|
||||
// 初始化选中菜单
|
||||
@@ -33,7 +33,7 @@
|
||||
import { vueAdmin } from "../VueAdmin";
|
||||
import { reactive, computed, onMounted } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import LangSwitch from "../components/LangSwitch.vue";
|
||||
import LangSwitch from "./ShrimpLangSwitch.vue";
|
||||
|
||||
vueAdmin.token = null;
|
||||
|
||||
@@ -33,10 +33,10 @@
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import navMenu from "./navMenu.vue";
|
||||
import Logo from "./logo.vue";
|
||||
import { ref } from "vue";
|
||||
import { vueAdmin } from '../VueAdmin';
|
||||
import navMenu from "./navMenu.vue";
|
||||
import Logo from "./logo.vue";
|
||||
|
||||
let nav = ref(false);
|
||||
function showMobileNav() { nav.value = true; }
|
||||
@@ -21,7 +21,7 @@
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { vueAdmin } from "../VueAdmin";
|
||||
import LangSwitch from "../components/LangSwitch.vue";
|
||||
import LangSwitch from "./ShrimpLangSwitch.vue";
|
||||
|
||||
function screen() {
|
||||
vueAdmin.fullscreen();
|
||||
+47
-4
@@ -2,10 +2,52 @@
|
||||
//
|
||||
// 消费侧用法见 README.md。本文件只做 re-export。
|
||||
|
||||
// ===== 类型契约(IShrimpType 本地副本,@syncedFrom shrimp-server contract 1.0.0)=====
|
||||
export {
|
||||
ShrimpCode,
|
||||
ShrimpError,
|
||||
ShrimpFieldTypes,
|
||||
ShrimpConfig,
|
||||
isShrimpCondition,
|
||||
} from './IShrimpType'
|
||||
|
||||
export type {
|
||||
ILabel,
|
||||
IShrimpResponse,
|
||||
IModuleInfo,
|
||||
ILoginResult,
|
||||
IMeResult,
|
||||
IMenuItem,
|
||||
ITableProto,
|
||||
ITableCrudProto,
|
||||
IUser,
|
||||
IRole,
|
||||
IOperationLog,
|
||||
WithId,
|
||||
IShrimpOperator,
|
||||
IShrimpPowerData,
|
||||
ShrimpRequestFn,
|
||||
IShrimpClient,
|
||||
ShrimpFieldType,
|
||||
FieldEditable,
|
||||
IFieldTypeHandler,
|
||||
IFieldConfig,
|
||||
IFieldRule,
|
||||
IPageQuery,
|
||||
IPageResult,
|
||||
IShrimpCondition,
|
||||
IShrimpPopulate,
|
||||
IShrimpQuery,
|
||||
IPowerItem,
|
||||
IUserProto,
|
||||
IRoleProto,
|
||||
} from './IShrimpType'
|
||||
|
||||
export {
|
||||
VueAdmin,
|
||||
vueAdmin,
|
||||
createShrimpAdmin,
|
||||
resolveVue,
|
||||
type ShrimpAdminOptions,
|
||||
type ShrimpAdminConfig,
|
||||
} from './VueAdmin'
|
||||
@@ -17,14 +59,15 @@ export {
|
||||
type IRouteInfo,
|
||||
} from './ShrimpClient'
|
||||
|
||||
// 框架组件 — 业务页面想直接复用就 import 这些
|
||||
// 框架组件 — 业务页面想直接复用就 import 这些。
|
||||
// 这些是「静态」导出,拿到的就是框架内置版本,不受消费侧 sources 影响。
|
||||
export { default as ShrimpTable } from './components/ShrimpTable.vue'
|
||||
export { default as ShrimpEditDrawer } from './components/ShrimpEditDrawer.vue'
|
||||
export { default as ShrimpFilterDrawer } from './components/ShrimpFilterDrawer.vue'
|
||||
export { default as ShrimpFilterTrigger } from './components/ShrimpFilterTrigger.vue'
|
||||
export { default as ShrimpSearchInput } from './components/ShrimpSearchInput.vue'
|
||||
export { default as PowerTree } from './components/PowerTree.vue'
|
||||
export { default as LangSwitch } from './components/LangSwitch.vue'
|
||||
export { default as ShrimpPowerTree } from './components/ShrimpPowerTree.vue'
|
||||
export { default as ShrimpLangSwitch } from './components/ShrimpLangSwitch.vue'
|
||||
|
||||
// 应用入口视图(消费侧 createApp 用)
|
||||
export { default as App } from './views/App.vue'
|
||||
export { default as App } from './App.vue'
|
||||
|
||||
+4
-1
@@ -25,7 +25,10 @@
|
||||
"enabled": "Enabled",
|
||||
"pressEnter": "Press Enter to add",
|
||||
"expand": "Expand",
|
||||
"collapse": "Collapse"
|
||||
"collapse": "Collapse",
|
||||
"back": "Back",
|
||||
"refresh": "Refresh",
|
||||
"notFound": "Not Found"
|
||||
},
|
||||
"user": {
|
||||
"username": "Username",
|
||||
|
||||
@@ -38,6 +38,7 @@
|
||||
"active": "启用状态",
|
||||
"createdAt": "创建时间",
|
||||
"updatedAt": "更新时间",
|
||||
"menuManage": "用户",
|
||||
"operationLog": "操作日志"
|
||||
},
|
||||
"operationLog": {
|
||||
@@ -55,6 +56,7 @@
|
||||
"powers": "权限",
|
||||
"createdAt": "创建时间",
|
||||
"updatedAt": "更新时间",
|
||||
"menuManage": "角色",
|
||||
"menuList": "角色列表",
|
||||
"empty": "暂无角色",
|
||||
"addRole": "新增角色",
|
||||
@@ -91,6 +93,9 @@
|
||||
"PWError": "请输入密码"
|
||||
},
|
||||
"power": {
|
||||
"user": "用户",
|
||||
"role": "角色",
|
||||
"zerobase": "Zero Base",
|
||||
"add": "新增",
|
||||
"edit": "编辑",
|
||||
"delete": "删除",
|
||||
|
||||
+3
-3
@@ -28,7 +28,7 @@
|
||||
<el-input v-model="formData.description" type="textarea" :rows="3" />
|
||||
</el-form-item>
|
||||
<el-form-item :label="$t('role.powers')">
|
||||
<PowerTree :modelValue="formData.powers || []" :allPowers="allPowers" :menuTree="vueAdmin.menuTree"
|
||||
<ShrimpPowerTree :modelValue="formData.powers || []" :allPowers="allPowers" :menuTree="vueAdmin.menuTree"
|
||||
@update:modelValue="val => formData.powers = val" />
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
@@ -51,9 +51,9 @@
|
||||
import { ref, onMounted } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { vueAdmin } from '../VueAdmin'
|
||||
import { IRole, IRoleProto, WithId, ILabel } from 'shrimp-server/types'
|
||||
import { IRole, IRoleProto, WithId, ILabel } from '../IShrimpType'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import PowerTree from '../components/PowerTree.vue'
|
||||
import ShrimpPowerTree from '../components/ShrimpPowerTree.vue'
|
||||
|
||||
interface IPowerItem {
|
||||
key: string
|
||||
|
||||
+6
-5
@@ -1,13 +1,14 @@
|
||||
<template>
|
||||
<ShrimpTable moduleKey="user" />
|
||||
<ShrimpTable moduleKey="user">
|
||||
<template #column-updatedAt="{ row }">
|
||||
<FieldRelativeTime :model-value="row.updatedAt" mode="display" :field="{}" />
|
||||
</template>
|
||||
</ShrimpTable>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import ShrimpTable from '../components/ShrimpTable.vue'
|
||||
import { vueAdmin } from '../VueAdmin'
|
||||
import FieldRelativeTime from './FieldRelativeTime.vue'
|
||||
|
||||
vueAdmin.overrideField('user', 'updatedAt', FieldRelativeTime)
|
||||
import FieldRelativeTime from '../components/fields/FieldRelativeTime.vue'
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
|
||||
@@ -14,8 +14,8 @@
|
||||
import { ref, computed, onMounted, watch } from 'vue'
|
||||
import { useRoute } from 'vue-router'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import ShrimpTable from '../../components/ShrimpTable.vue'
|
||||
import { vueAdmin } from '../../VueAdmin'
|
||||
import ShrimpTable from '../../components/ShrimpTable.vue'
|
||||
|
||||
const route = useRoute()
|
||||
const { t } = useI18n()
|
||||
|
||||
Reference in New Issue
Block a user