Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6bd334a937 | ||
|
|
4b6f260227 | ||
|
|
00c2211271 | ||
|
|
2ce6fd6d2f | ||
|
|
603e33d17f | ||
|
|
b7042c8387 | ||
|
|
bed4d4dc4a | ||
|
|
ab312fb24f | ||
|
|
546d95c926 | ||
|
|
6b0a6118e0 | ||
|
|
09ad43007a | ||
|
|
e789f8a1f7 | ||
|
|
d906603ce3 | ||
|
|
c49663e16e | ||
|
|
c44f2a159e | ||
|
|
35abfd831c | ||
|
|
3b0887b126 | ||
|
|
bba08dadcc | ||
|
|
701ed957ef | ||
|
|
0b75f8c6f2 | ||
|
|
417318921c | ||
|
|
f7ef29a928 | ||
|
|
f7ee862e0f | ||
|
|
8ac1427015 |
@@ -4,37 +4,160 @@ Shrimp 框架前端 —— 一种**经典解决方案**(不是框架本身),消
|
||||
|
||||
如果你想换 UI 库或者换前端技术栈,直接照 shrimp-server 的约定再写一份就行,不依赖本包。
|
||||
|
||||
## 安装
|
||||
shrimp-admin 是**源码 ship**(.ts + .vue 直接发),不带构建产物,由消费侧 Vite 编译。这省掉了框架的构建步骤,代价是**有几件事 npm 装完不会自动生效**,必须消费侧显式配 —— 下面的接入模板已经把它们全写进去了。
|
||||
|
||||
```bash
|
||||
npm i git+http://git.zeromvc.com/wc24/shrimp-admin.git#v0.3.0
|
||||
---
|
||||
|
||||
# 接入模板
|
||||
|
||||
> **整段抄,不要自己攒。** 标了「⚠️ 不能删」的行看起来多余,删掉的后果写在每行旁边;
|
||||
> 现存的 theseus-admin / hand-admin / bug-book 三个项目里,这些行一行不差全都在。
|
||||
|
||||
## 1. package.json
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"type": "module",
|
||||
"scripts": { "dev": "vite", "build": "vite build" },
|
||||
"dependencies": {
|
||||
"shrimp-admin": "git+http://git.zeromvc.com/wc24/shrimp-admin.git#v0.8.4",
|
||||
|
||||
// ⚠️ 不能删 —— 下面 7 个是 shrimp-admin 的 peerDependencies,
|
||||
// 必须由消费侧显式装进自己的 dependencies,不能指望 npm 提升碰巧能 import 到
|
||||
"vue": "^3.5.0",
|
||||
"vue-router": "^4.5.0",
|
||||
"vue-i18n": "^9.14.0",
|
||||
"axios": "^1.7.0",
|
||||
"element-plus": "^2.10.0",
|
||||
"@element-plus/icons-vue": "^2.3.0",
|
||||
"xlsx": "^0.18.5" // ⚠️ 不能删 —— ShrimpTable 的导入/导出按钮直接 import 它,少了 vite 起不来
|
||||
},
|
||||
"devDependencies": {
|
||||
"@vitejs/plugin-vue": "^5.2.0",
|
||||
"sass-embedded": "^1.80.0", // ⚠️ 不能删 —— shrimp-admin/style 是 .scss
|
||||
"typescript": "^5.6.0",
|
||||
"vite": "^6.0.0"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
shrimp-admin 是**源码 ship**(.ts + .vue 直接发),由消费侧 Vite 编译。
|
||||
服务端那侧另有一条硬约束:**shrimp-server 要求 Express 5**(它的兜底路由用了 `/*path` 具名通配,Express 4 只会当字面路径)。装成 4 的症状是能登录、能出菜单,但**所有** `POST /<moduleKey>/list` 都 404。
|
||||
|
||||
## 使用
|
||||
## 2. vite.config.ts
|
||||
|
||||
```ts
|
||||
import { defineConfig } from 'vite'
|
||||
import vue from '@vitejs/plugin-vue'
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [vue()],
|
||||
optimizeDeps: {
|
||||
// ⚠️ 不能删 —— 删了整页白屏,报 resolveVue: components/layout.vue not found in sources
|
||||
exclude: ['shrimp-admin'],
|
||||
},
|
||||
resolve: {
|
||||
// ⚠️ 不能删 —— 删了 element-plus 与 shrimp-admin 各带一份 vue/dayjs,互操作错位
|
||||
dedupe: ['vue', 'vue-i18n', 'vue-router', 'element-plus', 'dayjs'],
|
||||
},
|
||||
server: {
|
||||
// 开发期后台接口由 vite 转发,前端一律走相对路径,不注入任何后端地址
|
||||
proxy: { '/admin-api': { target: 'http://127.0.0.1:8080', changeOrigin: true } },
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
## 3. src/main.ts
|
||||
|
||||
```ts
|
||||
// main.ts
|
||||
import { createApp } from 'vue'
|
||||
import { createShrimpAdmin, App } from 'shrimp-admin'
|
||||
|
||||
// ⚠️ 不能删,且必须在 shrimp-admin/style 之前 ——
|
||||
// 删了页面能出来但整个掉样式,最显眼的症状是图标被撑到巨大
|
||||
import 'element-plus/dist/index.css'
|
||||
import 'element-plus/theme-chalk/display.css'
|
||||
import 'shrimp-admin/style'
|
||||
|
||||
import { createShrimpAdmin, App } from 'shrimp-admin'
|
||||
import zhCn from './locales/zh-cn.json'
|
||||
import en from './locales/en.json'
|
||||
|
||||
const app = createApp(App)
|
||||
app.use(createShrimpAdmin({
|
||||
config: {
|
||||
API_URL: '/admin-api',
|
||||
API_URL: '/admin-api', // 相对路径,由 vite proxy 转发
|
||||
TIMEOUT: 10000,
|
||||
},
|
||||
locales: { 'zh-cn': zhCn, en },
|
||||
// ⚠️ import.meta.glob 必须写在消费侧的文件里(vite 静态扫描相对本文件),
|
||||
// 不能封装成函数从别处调
|
||||
sources: import.meta.glob('./shrimp/**/*.vue'),
|
||||
}))
|
||||
app.mount('#app')
|
||||
```
|
||||
|
||||
## 唯一约定: `sources` 路径后缀覆盖
|
||||
## 4. 业务模块:默认什么都不用写
|
||||
|
||||
后端声明了几个 moduleKey,前端就自动有几个菜单、几张表 —— 字段、筛选、可用操作全在 moduleInfo 里,内置的 `module/_default.vue` 拿 moduleKey 渲染出来就是了。**不需要为每个模块建文件。**
|
||||
|
||||
只在有**真实增量**时才写 `src/shrimp/module/<key>.vue` 覆盖它(加列插槽、换布局、塞额外操作):
|
||||
|
||||
```vue
|
||||
<!-- src/shrimp/module/product.vue —— 后端 moduleKey === 'product' -->
|
||||
<template>
|
||||
<ShrimpTable moduleKey="product">
|
||||
<template #column-price="{ row }">
|
||||
<span :class="row.price > 1000 ? 'is-expensive' : ''">¥{{ row.price }}</span>
|
||||
</template>
|
||||
</ShrimpTable>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
// 字段、筛选、编辑仍由后端 moduleInfo 声明,这里只加自己那点增量
|
||||
import { ShrimpTable } from 'shrimp-admin'
|
||||
</script>
|
||||
```
|
||||
|
||||
内置的 `login.vue` / `layout.vue` / `404.vue` 同理,**一个都不用写**(见下面「唯一约定」)。
|
||||
|
||||
---
|
||||
|
||||
# 出错对照表
|
||||
|
||||
接入时按症状反查,不必先懂原理。
|
||||
|
||||
| 你看到的 | 病因 | 改哪 |
|
||||
| --- | --- | --- |
|
||||
| `resolveVue: components/layout.vue not found in sources`,整页白屏 | shrimp-admin 被 vite 预打包了 | vite.config `optimizeDeps.exclude: ['shrimp-admin']` |
|
||||
| `Failed to resolve import "xlsx"`,vite 起不来 | 少装 peerDependency `xlsx` | `npm i xlsx`,模板第 1 节 |
|
||||
| 页面出来了但没样式,**图标巨大** | 没引 element-plus 基础样式 | main.ts 加两行 css,模板第 3 节 |
|
||||
| 能登录、菜单也有,但**所有列表都 404** | 服务端装的是 Express 4 | 服务端升到 `express@^5` |
|
||||
| `does not provide an export named 'default'`(dayjs / element-plus) | 依赖被装了两份 | vite.config `resolve.dedupe`,模板第 2 节 |
|
||||
|
||||
## 验收: 必须在浏览器里打开页面
|
||||
|
||||
`vite build` 通过、`curl` 打接口通,**都不算接入完成**。上表前三行全部逃得过构建和接口测试:
|
||||
|
||||
- dev 用 esbuild 预打包、build 用 rollup,是**两套转换管线**。rollup 正确处理 node_modules 里的 `import.meta.glob`,所以第 1 行的问题在 `vite build` 下一路绿灯,只在 dev 复现。
|
||||
- 样式和路由注册只在浏览器运行时才成立,接口测试根本不经过它们。
|
||||
|
||||
# 那几行为什么不能删
|
||||
|
||||
## `optimizeDeps.exclude: ['shrimp-admin']`
|
||||
|
||||
Vite dev 默认用 **esbuild** 把 node_modules 里的裸导入预打包成 `node_modules/.vite/deps/shrimp-admin.js`。两个后果:
|
||||
|
||||
- 框架的内置组件表靠 `import.meta.glob('./{components,module}/**/*.vue')` 收集,这是 **Vite 编译期宏**,esbuild 不认识,会原样抄进产物;等它在 `.vite/deps/` 目录下才被展开时,那个目录里一个 `.vue` 都没有 → 内置表变成空对象 `{}` → 内置兜底全部落空。
|
||||
- 预打包等于复制出第二份模块实例,`vueAdmin` 单例会分裂成两个,消费侧拿到的和框架内部用的不是同一个。
|
||||
|
||||
## element-plus 的两行 css
|
||||
|
||||
`shrimp-admin/style` 只包含框架自己的覆盖样式与暗色变量(`fix.scss` / `dark.scss` 等),**不含** element-plus 本体的样式表。element-plus 是 peerDependency、由消费侧安装,它的基础样式自然也该由消费侧引 —— 框架替你引会锁死版本、也挡住你换主题。顺序不能反:覆盖必须在基础之后。
|
||||
|
||||
## `xlsx`
|
||||
|
||||
`ShrimpTable` 的导入/导出按钮是**静态** `import * as XLSX from 'xlsx'`,不是按需加载 —— 就算你的后台从不点那两个按钮,模块解析也绕不过去。它是 peerDependency 而不是 dependency,理由和 element-plus 一样:版本该由消费侧定。
|
||||
|
||||
# 唯一约定: `sources` 路径后缀覆盖
|
||||
|
||||
消费侧把所有要交给框架的 .vue 通过单个 `sources` 入口注入(`import.meta.glob` 必须由消费侧自己调用,vite 静态扫描相对调用文件)。框架按**文件路径后缀**匹配,同后缀消费侧优先,内置兜底。
|
||||
|
||||
@@ -47,22 +170,26 @@ app.mount('#app')
|
||||
│ └── fields/
|
||||
│ └── FieldRelativeTime.vue 注册字段类型 relativeTime
|
||||
└── module/
|
||||
├── product.vue 业务模块,routed by moduleKey
|
||||
├── product.vue 覆盖业务模块 product 的默认表格
|
||||
├── _default.vue 覆盖「所有没单独写壳的模块」用的那份
|
||||
└── user/
|
||||
└── orders.vue 子模块,parent=user
|
||||
```
|
||||
|
||||
### 覆盖颗粒度只在 3 个入口
|
||||
`module/` 下一个文件都没有也能跑 —— 那时每个模块都落到内置的 `module/_default.vue`。
|
||||
|
||||
框架内 .vue 之间的 peer 引用是**硬编码静态 import**,override 颗粒度就停在下面这 3 类入口,不会一路传递下去:
|
||||
### 覆盖颗粒度只在这几个入口
|
||||
|
||||
框架内 .vue 之间的 peer 引用是**硬编码静态 import**,override 颗粒度就停在下面这几类入口,不会一路传递下去:
|
||||
|
||||
| 入口 | 后缀 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| **router targets** | `components/login.vue`、`components/layout.vue`、`components/404.vue` | vue-router 三个根级路由组件 |
|
||||
| **module routes** | `module/<key>.vue`、`module/<parent>/<sub>.vue` | 走 `registerRoute` 的业务模块/子模块 |
|
||||
| **module routes** | `module/<key>.vue`、`module/<parent>/<sub>.vue`、`module/_default.vue` | 走 `registerRoute` 的业务模块/子模块;都没写就用内置 `_default` |
|
||||
| **field registry** | `components/fields/Field<X>.vue` | 字段类型注册表(文件名首字母小写 = type 键) |
|
||||
| **顶栏** | `components/userbar.vue` | 右上角那一条(语言、全屏、用户菜单),整体替换 |
|
||||
|
||||
想换更细的部件(比如 layout 里的 topbar)就在消费侧的 `layout.vue` 自己组装 — 框架不再代理任何 peer 切换。
|
||||
**表里没有的路径不会被覆盖,而且不报错**——写了个 `components/topbar.vue` 放进 sources,框架照样用内置那份,页面正常打开、你的文件被静默忽略。想换更细的部件就在消费侧的 `layout.vue` 里自己组装,框架不代理 peer 切换。
|
||||
|
||||
### 字段类型注册
|
||||
|
||||
@@ -74,11 +201,15 @@ app.mount('#app')
|
||||
| `FieldRelativeTime.vue` | `relativeTime` |
|
||||
| 你自己的 `FieldMyType.vue` | `myType` |
|
||||
|
||||
后端 moduleInfo 里 `field.type === 'myType'` 时就用你这个组件。内置类型: `string` / `boolean` / `date` / `json` / `number` / `password` / `relation` / `select` / `tab` / `textarea` / `relativeTime`。
|
||||
后端 moduleInfo 里 `field.type === 'myType'` 时就用你这个组件。
|
||||
|
||||
内置类型以 `src/components/fields/` 目录为准,当前是: `array` / `boolean` / `date` / `number` / `object` / `password` / `relation` / `relativeTime` / `select` / `string` / `tab` / `textarea`。其中 `relativeTime` 是本实现独有的,shrimp-server 的 `ShrimpFieldTypes` 里没有。
|
||||
|
||||
**没有 `json`。** 后端发一个没注册的 type 过来不会报错,`getFieldComponent` 静默回落成 `string` 渲染,只在控制台留一条 warning——列照样出、内容不对。字符串数组要用 `array` + `item`,嵌套对象用 `object` + `fields`。
|
||||
|
||||
### 业务模块
|
||||
|
||||
`module/<key>.vue` 命中 `moduleKey === '<key>'` 的路由,自动作为内容页。子表用嵌套目录(`module/<parent>/<sub>.vue`)。
|
||||
`module/<key>.vue` 命中 `moduleKey === '<key>'` 的路由,自动作为内容页。子表用嵌套目录(`module/<parent>/<sub>.vue`)。没写的模块落到 `module/_default.vue`,消费侧写一份同名文件即可整体换掉那个默认。
|
||||
|
||||
### 例子: 覆盖 login 页
|
||||
|
||||
@@ -130,7 +261,7 @@ function login() {
|
||||
|
||||
只要文件落在 `src/shrimp/components/login.vue`,被 `sources` 的 glob 扫到,框架的 `/login` 路由就会用你这份替换内置版本。
|
||||
|
||||
## 消费的契约
|
||||
# 消费的契约
|
||||
|
||||
参见 shrimp-server README `## 约定` 章节。本包消费以下条件契约:
|
||||
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "shrimp-admin",
|
||||
"version": "0.1.0",
|
||||
"version": "0.8.3",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "shrimp-admin",
|
||||
"version": "0.1.0",
|
||||
"version": "0.8.3",
|
||||
"dependencies": {
|
||||
"shrimp-server": "git+http://git.zeromvc.com/wc24/shrimp-server.git#v0.5.0"
|
||||
},
|
||||
|
||||
+7
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "shrimp-admin",
|
||||
"version": "0.3.0",
|
||||
"version": "0.8.4",
|
||||
"private": true,
|
||||
"description": "Shrimp 框架前端 — 消费 ShrimpServer + ShrimpTable 契约的经典 Vue3 + Element Plus 实现",
|
||||
"main": "src/index.ts",
|
||||
@@ -17,13 +17,18 @@
|
||||
"src",
|
||||
"README.md"
|
||||
],
|
||||
"scripts": {
|
||||
"check:contract": "node scripts/check-contract.mjs",
|
||||
"sync:contract": "node scripts/check-contract.mjs --fix"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"vue": "^3.3.0",
|
||||
"vue-router": "^4.0.0",
|
||||
"vue-i18n": "^9.0.0",
|
||||
"axios": "^1.0.0",
|
||||
"element-plus": "^2.0.0",
|
||||
"@element-plus/icons-vue": "^2.0.0"
|
||||
"@element-plus/icons-vue": "^2.0.0",
|
||||
"xlsx": "^0.18.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^20.0.0",
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
/**
|
||||
* 契约副本工具:比对 / 同步 src/IShrimpType.ts 与 shrimp-server 那份。
|
||||
*
|
||||
* node scripts/check-contract.mjs 比对,漂了就非零退出
|
||||
* node scripts/check-contract.mjs --fix 从 shrimp-server 复制过来(自动保留前端副本的注释头)
|
||||
*
|
||||
* 为什么需要它:副本靠人工同步,漂了一整代都没被发现——
|
||||
* 副本停在旧的 json 类型、缺 object/array/fields/item/parse/refs。
|
||||
* 前端对未注册的字段类型静默回落到 string,所以漂移不报错、只悄悄渲染错。
|
||||
* (同样是"改了就复制过去"的约定,goby 的 GobyClient.ts 四份拷贝已经全漂了,
|
||||
* 区别只在于那份复制后归消费侧拥有、漂了无所谓,而这份两边必须字节一致。)
|
||||
*
|
||||
* 只比对注释块之后的正文:两边的头部本来就该不同,一份是契约、一份声明自己是副本。
|
||||
*/
|
||||
import { readFileSync, writeFileSync, existsSync } from "node:fs"
|
||||
import { fileURLToPath } from "node:url"
|
||||
import { dirname, resolve } from "node:path"
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const mine = resolve(here, "../src/IShrimpType.ts")
|
||||
const fix = process.argv.includes("--fix")
|
||||
const argPath = process.argv.find(a => !a.startsWith("--") && a !== process.argv[0] && a !== process.argv[1])
|
||||
|
||||
const theirs = [
|
||||
argPath && resolve(argPath, "src/IShrimpType.ts"),
|
||||
resolve(here, "../node_modules/shrimp-server/src/IShrimpType.ts"),
|
||||
resolve(here, "../../shrimp-server/src/IShrimpType.ts"),
|
||||
].filter(Boolean).find(existsSync)
|
||||
|
||||
if (!theirs) {
|
||||
// 消费侧的前端项目不装后端包,找不到是正常的,不该让它们的构建挂掉
|
||||
console.log("skip: 找不到 shrimp-server 源码,无从比对")
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
const split = f => {
|
||||
const s = readFileSync(f, "utf8")
|
||||
const i = s.indexOf("*/") + 2
|
||||
return { head: s.slice(0, i), body: s.slice(i) }
|
||||
}
|
||||
|
||||
const a = split(mine)
|
||||
const b = split(theirs)
|
||||
|
||||
if (a.body === b.body) {
|
||||
console.log("✅ 契约副本与 shrimp-server 一致")
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
if (fix) {
|
||||
writeFileSync(mine, a.head + b.body)
|
||||
console.log("✅ 已从 shrimp-server 同步契约副本(保留原注释头)")
|
||||
console.log(" " + theirs + "\n → " + mine)
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
console.error("❌ 契约副本已漂移")
|
||||
console.error(" 副本: " + mine)
|
||||
console.error(" 契约: " + theirs)
|
||||
console.error(" 修法: npm run sync:contract")
|
||||
process.exit(1)
|
||||
+18
-7
@@ -1,15 +1,18 @@
|
||||
/**
|
||||
* Shrimp 类型契约 — 前后端 wire protocol 定义(前端副本)
|
||||
*
|
||||
* @syncedFrom shrimp-server contract 1.0.0
|
||||
* 这是 shrimp-server/src/IShrimpType.ts 的逐字副本(除本注释块外)。
|
||||
* 不要在这里改 wire protocol,先改 shrimp-server 那份升版本,再整份 cp 过来。
|
||||
*
|
||||
* 这是 shrimp-server/src/IShrimpType.ts 的逐字副本。
|
||||
* 不要在这里改 wire protocol,先改 shrimp-server 那份升版本,再 copy 过来更新 @syncedFrom。
|
||||
* 本文件由 shrimp-server 的 postbuild 自动同步过来,手改会被下次 build 覆盖。
|
||||
* 手动同步: npm run sync:contract 只想看漂没漂: npm run check:contract
|
||||
* 自动同步这件事存在的原因是:曾经靠人工复制,漂了一整代都没人发现——
|
||||
* 副本停在旧的 json 类型、缺 object/array/fields/item/parse/refs,
|
||||
* 而前端对未注册类型静默回落到 string,所以漂移不会报错、只会悄悄渲染错。
|
||||
*
|
||||
* 故意保留副本而不 import 'shrimp-server' 的原因:
|
||||
* - shrimp-server 入口会把 mongoose / express 牵进前端 bundle
|
||||
* - 拆 './types' 子入口会绕开 vite optimize、可读性也差
|
||||
* - 类型契约低频改动,版本号对照即可
|
||||
* - shrimp-server 默认入口会把 mongoose / express 牵进前端 bundle
|
||||
* - 前端项目不该为一份纯类型去装后端包
|
||||
*/
|
||||
|
||||
/** 业务错误码 */
|
||||
@@ -238,8 +241,9 @@ export const ShrimpFieldTypes = {
|
||||
Textarea: "textarea" as ShrimpFieldType,
|
||||
Password: "password" as ShrimpFieldType,
|
||||
Relation: "relation" as ShrimpFieldType,
|
||||
Json: "json" as ShrimpFieldType,
|
||||
Tab: "tab" as ShrimpFieldType,
|
||||
Object: "object" as ShrimpFieldType,
|
||||
Array: "array" as ShrimpFieldType,
|
||||
}
|
||||
|
||||
/** 字段可编辑状态 */
|
||||
@@ -279,6 +283,12 @@ export interface IFieldConfig {
|
||||
rules?: IFieldRule[] // 通用验证规则(前后端共用)
|
||||
/** tab 类型专用:每个 type 对应的子字段配置 */
|
||||
tabs?: { key: any; label: ILabel; fields: IFieldConfig[] }[]
|
||||
/** object 类型专用:嵌套字段组 */
|
||||
fields?: IFieldConfig[]
|
||||
/** array 类型专用:每个元素的字段配置(递归 IFieldConfig;元素无需 key,label 用作每项标题) */
|
||||
item?: IFieldConfig
|
||||
/** tab 类型专用:import 反序列化(把字符串还原成对象,如 xlsx 导入),默认 JSON.parse */
|
||||
parse?: (text: string) => any
|
||||
}
|
||||
|
||||
/** 通用验证规则(前后端共用) */
|
||||
@@ -315,6 +325,7 @@ export interface IPageResult<T> {
|
||||
page: number // 当前页码
|
||||
pageSize: number // 每页数量
|
||||
totalPages: number // 总页数
|
||||
refs?: Record<string, Record<string, any>> // relation 显示名字典: { moduleKey: { id: 显示名 } },前端显示时查名,替代逐行 _label
|
||||
}
|
||||
|
||||
// ============== 数据源查询协议 ==============
|
||||
|
||||
+41
-3
@@ -78,6 +78,15 @@ export function resolveVue(suffix: string): VueLoader {
|
||||
for (const key in internalSources) {
|
||||
if (key.endsWith(tail)) return internalSources[key] as any
|
||||
}
|
||||
// 内置表整个是空的,说明本包被 esbuild 预打包了——import.meta.glob 是 vite 编译期宏,
|
||||
// 预打包不认它,内置组件一个都收不到。报"找不到 layout.vue"会把人引向错误的方向。
|
||||
if (Object.keys(internalSources).length === 0) {
|
||||
throw new Error(
|
||||
`[shrimp-admin] 内置组件表为空,本包没有被 vite 正常转换。\n` +
|
||||
` 消费侧 vite.config 需要: optimizeDeps: { exclude: ["shrimp-admin"] }\n` +
|
||||
` (或直接用 shrimp-admin/vite 提供的插件,它会自动加上)`
|
||||
)
|
||||
}
|
||||
throw new Error(`[shrimp-admin] resolveVue: ${suffix} not found in sources`)
|
||||
}
|
||||
|
||||
@@ -88,6 +97,19 @@ export function resolveVue(suffix: string): VueLoader {
|
||||
|
||||
const fieldRegistry = new Map<string, Component>()
|
||||
|
||||
/** 未注册类型每种只喊一次——表格逐格调 getFieldComponent,不去重会刷屏 */
|
||||
const warnedTypes = new Set<string>()
|
||||
function warnOnce(type: string, moduleKey?: string, fieldKey?: string) {
|
||||
if (warnedTypes.has(type)) return
|
||||
warnedTypes.add(type)
|
||||
console.warn(
|
||||
`[shrimp-admin] 字段类型 "${type}" 没有对应组件,已按 string 渲染` +
|
||||
(moduleKey || fieldKey ? `(出现在 ${moduleKey ?? '?'}.${fieldKey ?? '?'})` : '') +
|
||||
`\n 已注册: ${[...fieldRegistry.keys()].sort().join(', ')}` +
|
||||
`\n 要么后端把 type 改成上面之一,要么消费侧补一个 shrimp/components/fields/Field${type.charAt(0).toUpperCase() + type.slice(1)}.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
|
||||
@@ -123,9 +145,22 @@ export class VueAdmin extends ShrimpClient {
|
||||
userName = ''
|
||||
config: ShrimpAdminConfig
|
||||
langList: { lang: string; name: string }[]
|
||||
/** 已注册成功的模块路由(moduleKey → IRouteInfo),供 relation 跳转/单项查看解析路由 */
|
||||
moduleRoutes = new Map<string, IRouteInfo>()
|
||||
|
||||
getFieldComponent(_moduleKey: string, type: string, _fieldKey?: string): Component {
|
||||
return fieldRegistry.get(type) || fieldRegistry.get('string')!
|
||||
const hit = fieldRegistry.get(type)
|
||||
if (hit) return hit
|
||||
// 类型词汇表是开放的(消费侧放个 Field<X>.vue 就能扩),所以这里不能报错、只能回落。
|
||||
// 但静默回落等于打错字永远发现不了——曾经有个 json 类型这么活了一整代。
|
||||
warnOnce(type, _moduleKey, _fieldKey)
|
||||
return fieldRegistry.get('string')!
|
||||
}
|
||||
|
||||
/** 目标模块能否作为「单项查看」跳转目标:已按权限注册路由 且 非子模块。返回其路由信息或 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 })
|
||||
@@ -246,8 +281,10 @@ export class VueAdmin extends ShrimpClient {
|
||||
try {
|
||||
importer = resolveVue(`module/${componentPath}.vue`)
|
||||
} catch {
|
||||
console.warn(`[shrimp-admin] module component not found: module/${componentPath}.vue`)
|
||||
return
|
||||
// 消费侧没给这个模块的壳,用内置通用表格顶上。
|
||||
// moduleKey 下面本来就当 props 传下去,而 ShrimpTable 要的只有它——
|
||||
// 「后端声明了模块,前端就该渲染出来」是本包消费的契约,缺一个壳不该让菜单点不开。
|
||||
importer = resolveVue("module/_default.vue")
|
||||
}
|
||||
this.router.addRoute("layout", {
|
||||
path: info.path || "/" + info.name,
|
||||
@@ -256,6 +293,7 @@ export class VueAdmin extends ShrimpClient {
|
||||
props: { moduleKey: info.moduleKey, events: info.events },
|
||||
meta: { title: info.label }
|
||||
})
|
||||
this.moduleRoutes.set(info.moduleKey, info)
|
||||
}
|
||||
|
||||
initRouter() {
|
||||
|
||||
@@ -4,11 +4,18 @@
|
||||
<el-form :model="localFilterData">
|
||||
<template v-for="field in filterableFields" :key="field.key">
|
||||
<el-form-item :label="vueAdmin.t(field.label)">
|
||||
<div class="filter-field-row">
|
||||
<div class="filter-field-control">
|
||||
<slot :name="`filter-${field.key}`" :field="field" :data="localFilterData">
|
||||
<component :is="vueAdmin.getFieldComponent(moduleKey, field.type, field.key)" :field="field"
|
||||
:model-value="localFilterData[field.key]"
|
||||
<component :is="vueAdmin.getFieldComponent(moduleKey, field.type, field.key)"
|
||||
:field="field" :model-value="localFilterData[field.key]"
|
||||
@update:model-value="onFieldChange(field.key, $event)" mode="filter" />
|
||||
</slot>
|
||||
</div>
|
||||
<!-- 单独清空该字段:常驻、无值时禁用(不 v-if,避免按钮显隐导致布局闪动) -->
|
||||
<el-button link :icon="CircleClose" class="filter-clear"
|
||||
:disabled="!hasValue(field.key)" @click="clearField(field.key)" />
|
||||
</div>
|
||||
</el-form-item>
|
||||
</template>
|
||||
</el-form>
|
||||
@@ -21,6 +28,7 @@
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { ref, watch } from 'vue'
|
||||
import { CircleClose } from '@element-plus/icons-vue'
|
||||
import { IFieldConfig } from '../IShrimpType'
|
||||
import { vueAdmin } from '../VueAdmin'
|
||||
|
||||
@@ -68,6 +76,21 @@ function onFieldChange(key: string, value: any) {
|
||||
localFilterData.value = { ...localFilterData.value, [key]: value }
|
||||
}
|
||||
|
||||
// 该字段当前是否有筛选值(决定单独清空按钮是否出现);范围 {gte,lte}/数组按内容判空
|
||||
function hasValue(key: string): boolean {
|
||||
const v = localFilterData.value[key]
|
||||
if (v == null || v === '') return false
|
||||
if (Array.isArray(v)) return v.length > 0
|
||||
if (typeof v === 'object') return Object.keys(v).length > 0
|
||||
return true
|
||||
}
|
||||
|
||||
// 单独清空某个字段:只摘掉这一个 key,其余筛选条件不动
|
||||
function clearField(key: string) {
|
||||
const { [key]: _, ...rest } = localFilterData.value
|
||||
localFilterData.value = rest
|
||||
}
|
||||
|
||||
function handleReset() {
|
||||
closedByReset.value = true
|
||||
localFilterData.value = {}
|
||||
@@ -101,4 +124,23 @@ function handleConfirm() {
|
||||
.shrimp-drawer .el-drawer__body .el-form-item {
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.filter-field-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.filter-field-control {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.filter-clear {
|
||||
flex: none;
|
||||
padding: 0;
|
||||
font-size: 16px;
|
||||
color: var(--el-text-color-secondary);
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -29,13 +29,13 @@
|
||||
<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' ? { displayLabel: row[field.key + '_label'] } : {}" />
|
||||
</slot>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</template>
|
||||
|
||||
<el-table-column :label="$t('base.operation')" :width="rowActionsWidth" v-if="hasRowActions">
|
||||
<el-table-column :label="$t('base.operation')" :width="resolvedRowActionsWidth" v-if="hasRowActions">
|
||||
<template #default="{ row }">
|
||||
<el-button v-if="hasActiveField && can('edit')" link :type="row.active ? 'warning' : 'success'" :icon="row.active ? VideoPause : VideoPlay" size="large" @click="handleToggleActive(row)" />
|
||||
<el-button v-if="can('edit')" link type="primary" :icon="Edit" size="large" @click="handleEdit(row)" />
|
||||
@@ -78,7 +78,7 @@
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { ref, computed, useSlots, onMounted, type Component } from 'vue'
|
||||
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'
|
||||
@@ -100,6 +100,8 @@ interface Props {
|
||||
pageSize?: number
|
||||
/** 显式锁定的筛选条件(覆盖自动 ownerKey 推断);用户无法修改,会合并进 filter 并在筛选抽屉中隐藏 */
|
||||
baseFilter?: Record<string, any>
|
||||
/** 显式指定操作列宽度;传入后覆盖按内置按钮数量自动计算的宽度,适用于 row-actions 插槽塞了多个按钮的场景 */
|
||||
rowActionsWidth?: number | string
|
||||
}
|
||||
|
||||
const props = withDefaults(defineProps<Props>(), {
|
||||
@@ -132,8 +134,18 @@ const {
|
||||
|
||||
const searchVisible = ref(false)
|
||||
|
||||
// relation 跳转用 ?filter={_id} 锁定单条;_id 是隐形 pin(不在筛选抽屉里),
|
||||
// 用户一旦搜索/改筛选就清掉它,避免被看不见的 _id 一直 AND 着导致结果莫名为空
|
||||
function stripJumpPin() {
|
||||
if ('_id' in filterData.value) {
|
||||
const { _id, ...rest } = filterData.value
|
||||
filterData.value = rest
|
||||
}
|
||||
}
|
||||
|
||||
function onSearch() {
|
||||
searchKeyword.value = keyword.value
|
||||
stripJumpPin()
|
||||
currentPage.value = 1
|
||||
refresh()
|
||||
}
|
||||
@@ -151,7 +163,8 @@ const hasFilter = computed(() => {
|
||||
})
|
||||
|
||||
async function handleFilterConfirm(newFilterData: Record<string, any>) {
|
||||
filterData.value = newFilterData
|
||||
const { _id, ...rest } = newFilterData // 确认筛选 → 丢弃跳转 pin
|
||||
filterData.value = rest
|
||||
currentPage.value = 1
|
||||
await refresh()
|
||||
}
|
||||
@@ -201,9 +214,24 @@ const formFields = computed(() => {
|
||||
return list.filter(f => f.editable !== 'readonly')
|
||||
})
|
||||
const searchableFields = computed(() => fields.value.filter(f => f.searchable))
|
||||
// 递归收集 filterable 字段(含 object/tab 嵌套叶子),生成 key=点路径的"合成字段"。
|
||||
// 这样筛选抽屉/buildFilter/URL 同步全按 field.key 走即可——key 就是 condition.level 这种路径。
|
||||
function collectFilterablePaths(list: IFieldConfig[], base: string[], out: any[]) {
|
||||
for (const f of list) {
|
||||
const path = [...base, f.key]
|
||||
if (f.filterable) out.push({ ...f, key: path.join('.') })
|
||||
if (f.type === 'tab' && Array.isArray((f as any).tabs)) {
|
||||
for (const t of (f as any).tabs) collectFilterablePaths(t.fields, path, out)
|
||||
} else if (f.type === 'object' && Array.isArray((f as any).fields)) {
|
||||
collectFilterablePaths((f as any).fields, path, out)
|
||||
}
|
||||
}
|
||||
}
|
||||
const filterableFields = computed(() => {
|
||||
const lockedKeys = new Set(Object.keys(props.baseFilter || {}))
|
||||
return fields.value.filter(f => f.filterable && !lockedKeys.has(f.key))
|
||||
const out: any[] = []
|
||||
collectFilterablePaths(fields.value, [], out)
|
||||
return out.filter(f => !lockedKeys.has(f.key))
|
||||
})
|
||||
|
||||
const formSlotNames = computed(() => Object.keys(slots).filter(name => name.startsWith('form-')))
|
||||
@@ -214,6 +242,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)
|
||||
|
||||
// ---- 对话框状态 ----
|
||||
|
||||
@@ -258,7 +289,8 @@ function handleSubJump(sub: IModuleInfo, row: any) {
|
||||
|
||||
const hasRowActions = computed(() => can('edit') || can('delete') || hasActiveField.value || subModules.value.length > 0 || !!slots['row-actions'])
|
||||
|
||||
const rowActionsWidth = computed(() => {
|
||||
const resolvedRowActionsWidth = computed(() => {
|
||||
if (props.rowActionsWidth != null && props.rowActionsWidth !== '') return props.rowActionsWidth
|
||||
let n = 0
|
||||
if (hasActiveField.value && can('edit')) n++
|
||||
if (can('edit')) n++
|
||||
@@ -293,8 +325,10 @@ async function handleAdd() {
|
||||
formData.value[field.key] = false
|
||||
} else if (field.type === 'number') {
|
||||
formData.value[field.key] = 0
|
||||
} else if (field.multiple) {
|
||||
} else if (field.type === 'array' || field.multiple) {
|
||||
formData.value[field.key] = []
|
||||
} else if (field.type === 'object') {
|
||||
formData.value[field.key] = {}
|
||||
} else {
|
||||
formData.value[field.key] = ''
|
||||
}
|
||||
@@ -320,8 +354,10 @@ async function handleSave() {
|
||||
formFields.value.forEach(field => {
|
||||
if (field.editable === 'readonly') return
|
||||
if (field.editable === 'addOnly') return
|
||||
const newValue = formData.value[field.key]
|
||||
const oldValue = originalData.value[field.key]
|
||||
// 清空字段值为 undefined 时,JSON.stringify 会丢键 → 后端收不到、看似"提交无效"。
|
||||
// 归一成 null:既保证清空能提交(后端置空),又让"两边都空"不误判为有改动。
|
||||
const newValue = formData.value[field.key] ?? null
|
||||
const oldValue = originalData.value[field.key] ?? null
|
||||
if (newValue === oldValue) return
|
||||
submitData[field.key] = newValue
|
||||
})
|
||||
@@ -426,7 +462,16 @@ async function handleExport() {
|
||||
}
|
||||
if (ownerId.value) query.ownerId = ownerId.value
|
||||
const list = await api.export(query)
|
||||
const ws = XLSX.utils.json_to_sheet(list)
|
||||
// 后端只发原始对象;xlsx 单元格放不下对象/数组(会变 [object Object]),这里通用地 JSON 序列化
|
||||
// (覆盖 tab 等结构化字段)。import 时这些字符串由后端各类型 reqFilter 还原。
|
||||
const rows = list.map((row: Record<string, any>) => {
|
||||
const out: Record<string, any> = {}
|
||||
for (const [k, v] of Object.entries(row)) {
|
||||
out[k] = (v !== null && typeof v === 'object') ? JSON.stringify(v) : v
|
||||
}
|
||||
return out
|
||||
})
|
||||
const ws = XLSX.utils.json_to_sheet(rows)
|
||||
const wb = XLSX.utils.book_new()
|
||||
XLSX.utils.book_append_sheet(wb, ws, props.moduleKey)
|
||||
XLSX.writeFile(wb, `${props.moduleKey}_export_${Date.now()}.xlsx`)
|
||||
@@ -501,6 +546,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
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
<template>
|
||||
<!-- 显示:逐元素递归渲染 item 的 display 组件 -->
|
||||
<template v-if="mode === 'display'">
|
||||
<span v-if="!items.length">-</span>
|
||||
<span v-else class="arr-display">
|
||||
<span v-for="(el, i) in items" :key="i" class="arr-chip">
|
||||
<component :is="vueAdmin.getFieldComponent(moduleKey, field.item.type, '')"
|
||||
:field="field.item" :model-value="el" mode="display" />
|
||||
</span>
|
||||
</span>
|
||||
</template>
|
||||
<!-- 编辑:每项一行(标题 + item 编辑组件 + 删除),底部添加。第一版从简:无排序拖拽 -->
|
||||
<div v-else class="field-array">
|
||||
<div v-for="(el, i) in items" :key="i" class="arr-row">
|
||||
<div class="arr-head">
|
||||
<span class="arr-idx">{{ itemTitle }} #{{ i + 1 }}</span>
|
||||
<el-button type="danger" text size="small" @click="removeAt(i)">删除</el-button>
|
||||
</div>
|
||||
<component :is="vueAdmin.getFieldComponent(moduleKey, field.item.type, '')"
|
||||
:field="field.item" :model-value="el"
|
||||
@update:model-value="setAt(i, $event)" mode="edit" :disabled="disabled" />
|
||||
</div>
|
||||
<el-button type="primary" text @click="addOne" :disabled="disabled">+ 添加{{ itemTitle }}</el-button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { computed, inject } from 'vue'
|
||||
import { vueAdmin } from '../../VueAdmin'
|
||||
|
||||
const props = defineProps<{
|
||||
field: any
|
||||
modelValue: any
|
||||
mode: 'display' | 'edit' | 'filter'
|
||||
disabled?: boolean
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{ 'update:modelValue': [value: any] }>()
|
||||
|
||||
const moduleKey = inject('shrimpModuleKey', '')
|
||||
|
||||
const items = computed<any[]>(() => Array.isArray(props.modelValue) ? props.modelValue : [])
|
||||
const itemTitle = computed(() => vueAdmin.t(props.field.item?.label) || '项')
|
||||
|
||||
function setAt(i: number, value: any) {
|
||||
const arr = items.value.slice()
|
||||
arr[i] = value
|
||||
emit('update:modelValue', arr)
|
||||
}
|
||||
function removeAt(i: number) {
|
||||
const arr = items.value.slice()
|
||||
arr.splice(i, 1)
|
||||
emit('update:modelValue', arr)
|
||||
}
|
||||
function addOne() {
|
||||
emit('update:modelValue', [...items.value, defaultOf(props.field.item)])
|
||||
}
|
||||
|
||||
/** 按 item schema 递归生成一个默认元素 */
|
||||
function defaultOf(schema: any): any {
|
||||
if (!schema) return null
|
||||
if (schema.defaultValue !== undefined) return schema.defaultValue
|
||||
if (schema.type === 'object') {
|
||||
const obj: any = {}
|
||||
for (const f of schema.fields || []) obj[f.key] = defaultOf(f)
|
||||
return obj
|
||||
}
|
||||
if (schema.type === 'array') return []
|
||||
if (schema.type === 'number') return 0
|
||||
if (schema.type === 'boolean') return false
|
||||
return null
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.arr-display {
|
||||
display: inline-flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 4px 12px;
|
||||
}
|
||||
|
||||
.field-array {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.arr-row {
|
||||
padding: 8px 10px;
|
||||
border: 1px solid var(--el-border-color-lighter);
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
.arr-head {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
|
||||
.arr-idx {
|
||||
color: var(--el-text-color-secondary);
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
}
|
||||
</style>
|
||||
@@ -42,7 +42,7 @@
|
||||
style="width: 100%"
|
||||
/>
|
||||
<el-date-picker v-else :model-value="modelValue" @update:model-value="$emit('update:modelValue', $event)" :disabled="disabled"
|
||||
type="datetime" style="width: 100%" />
|
||||
type="datetime" :clearable="!field.required" style="width: 100%" />
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
<template>
|
||||
<template v-if="mode === 'display'">
|
||||
<el-tooltip v-if="modelValue != null" :content="displayValue" placement="top">
|
||||
<span class="json-display">{{ displayValue }}</span>
|
||||
</el-tooltip>
|
||||
<span v-else>-</span>
|
||||
</template>
|
||||
<el-input
|
||||
v-else
|
||||
:model-value="modelValue"
|
||||
@update:model-value="$emit('update:modelValue', $event)"
|
||||
type="textarea"
|
||||
:rows="4"
|
||||
:disabled="disabled"
|
||||
placeholder="请输入 JSON"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { computed } from 'vue'
|
||||
|
||||
const props = defineProps<{
|
||||
field: any
|
||||
modelValue: any
|
||||
mode: 'display' | 'edit' | 'filter'
|
||||
disabled?: boolean
|
||||
}>()
|
||||
|
||||
defineEmits<{
|
||||
'update:modelValue': [value: any]
|
||||
}>()
|
||||
|
||||
const displayValue = computed(() => {
|
||||
if (props.modelValue == null) return ''
|
||||
if (typeof props.modelValue === 'string') return props.modelValue
|
||||
return JSON.stringify(props.modelValue, null, 2)
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.json-display {
|
||||
display: inline-block;
|
||||
max-width: 200px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,69 @@
|
||||
<template>
|
||||
<!-- 显示:递归渲染各子字段的 display 组件(relation 子查 refs) -->
|
||||
<template v-if="mode === 'display'">
|
||||
<span v-if="!modelValue || typeof modelValue !== 'object'">-</span>
|
||||
<span v-else class="obj-display">
|
||||
<span v-for="f in field.fields || []" :key="f.key" class="obj-child">
|
||||
<span class="obj-label">{{ vueAdmin.t(f.label) }}:</span>
|
||||
<component :is="vueAdmin.getFieldComponent(moduleKey, f.type, f.key)"
|
||||
:field="f" :model-value="(modelValue || {})[f.key]" mode="display" />
|
||||
</span>
|
||||
</span>
|
||||
</template>
|
||||
<!-- 编辑:每个子字段一行,递归渲染 edit 组件 -->
|
||||
<div v-else class="field-object">
|
||||
<el-form-item v-for="f in field.fields || []" :key="f.key" :label="vueAdmin.t(f.label)" :required="f.required">
|
||||
<component :is="vueAdmin.getFieldComponent(moduleKey, f.type, f.key)"
|
||||
:field="f" :model-value="(modelValue || {})[f.key]"
|
||||
@update:model-value="onChild(f.key, $event)" mode="edit" :disabled="disabled" />
|
||||
</el-form-item>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { inject } from 'vue'
|
||||
import { vueAdmin } from '../../VueAdmin'
|
||||
|
||||
const props = defineProps<{
|
||||
field: any
|
||||
modelValue: any
|
||||
mode: 'display' | 'edit' | 'filter'
|
||||
disabled?: boolean
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{ 'update:modelValue': [value: any] }>()
|
||||
|
||||
const moduleKey = inject('shrimpModuleKey', '')
|
||||
|
||||
function onChild(key: string, value: any) {
|
||||
emit('update:modelValue', { ...(props.modelValue || {}), [key]: value })
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.obj-display {
|
||||
display: inline-flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 4px 10px;
|
||||
}
|
||||
|
||||
.obj-child {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.obj-label {
|
||||
color: var(--el-text-color-secondary);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.field-object {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
padding-left: 12px;
|
||||
border-left: 2px solid var(--el-border-color-lighter);
|
||||
}
|
||||
</style>
|
||||
@@ -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'"
|
||||
@@ -12,13 +18,13 @@
|
||||
>
|
||||
<el-option v-for="opt in options" :key="opt.value" :label="opt.label" :value="opt.value" />
|
||||
</el-select>
|
||||
<el-select v-else :model-value="stringValue" @update:model-value="$emit('update:modelValue', $event)" :disabled="disabled" :multiple="field.multiple" filterable remote :remote-method="onSearch" :loading="loading" style="width: 100%">
|
||||
<el-select v-else :model-value="stringValue" @update:model-value="onEdit" :disabled="disabled" :multiple="field.multiple" :clearable="!field.required" filterable remote :remote-method="onSearch" :loading="loading" style="width: 100%">
|
||||
<el-option v-for="opt in options" :key="opt.value" :label="opt.label" :value="opt.value" />
|
||||
</el-select>
|
||||
</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 '../../IShrimpType'
|
||||
|
||||
@@ -27,16 +33,45 @@ const props = defineProps<{
|
||||
modelValue: any
|
||||
mode: 'display' | 'edit' | 'filter'
|
||||
disabled?: boolean
|
||||
displayLabel?: string | string[]
|
||||
}>()
|
||||
|
||||
defineEmits<{
|
||||
const emit = defineEmits<{
|
||||
'update:modelValue': [value: any]
|
||||
}>()
|
||||
|
||||
// 编辑态清空:el-select 单选清空发 '' 或 undefined,relation 是 ObjectId、且 undefined 会被
|
||||
// JSON.stringify 丢键 → 都归一成 null(取消关联)。多选清空是 [],原样。
|
||||
function onEdit(v: any) {
|
||||
emit('update:modelValue', v === '' || v == null ? (props.field.multiple ? [] : null) : v)
|
||||
}
|
||||
|
||||
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 +127,13 @@ onMounted(async () => {
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.rel-link {
|
||||
color: var(--el-color-primary);
|
||||
cursor: pointer;
|
||||
}
|
||||
.rel-link:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
@update:model-value="$emit('update:modelValue', $event)"
|
||||
:disabled="disabled"
|
||||
:multiple="field.multiple"
|
||||
:clearable="!field.required"
|
||||
style="width: 100%"
|
||||
>
|
||||
<el-option v-for="opt in resolvedOptions" :key="opt.value" :label="vueAdmin.t(opt.label)" :value="opt.value" />
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
</el-tag>
|
||||
<el-input v-model="inputValue" @keyup.enter="addTag" @blur="addTag" :placeholder="$t('base.pressEnter')" />
|
||||
</div>
|
||||
<el-input v-else :model-value="modelValue" @update:model-value="$emit('update:modelValue', $event)" :disabled="disabled" clearable />
|
||||
<el-input v-else :model-value="modelValue" @update:model-value="$emit('update:modelValue', $event)" :disabled="disabled" :clearable="!field.required" />
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
|
||||
@@ -1,13 +1,21 @@
|
||||
<template>
|
||||
<template v-if="mode === 'display'">
|
||||
<span v-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>
|
||||
<!-- 显示=前端递归渲染:分支标签 + 选中分支子字段。没选 type(清空) → 显示 - -->
|
||||
<span v-if="!modelValue || typeof modelValue !== 'object' || modelValue.type == null">-</span>
|
||||
<span v-else class="tab-display">
|
||||
<span class="tab-branch">{{ branchLabel }}</span>
|
||||
<span v-for="childField in selectedTab?.fields || []" :key="childField.key" class="tab-child">
|
||||
<span class="tab-child-label">{{ vueAdmin.t(childField.label) }}:</span>
|
||||
<component :is="vueAdmin.getFieldComponent(moduleKey, childField.type, childField.key)"
|
||||
:field="childField" :model-value="(modelValue || {})[childField.key]" mode="display" />
|
||||
</span>
|
||||
</span>
|
||||
</template>
|
||||
<div v-else class="field-tab">
|
||||
<el-form-item :label="vueAdmin.t(field.label) + ' - 类型'" :required="field.required">
|
||||
<el-select :model-value="innerValue.type" @update:model-value="onTypeChange" :disabled="disabled">
|
||||
<!-- 非必填可清空 → 清空后 type=null、整个 tab 置空、下面分支消失 -->
|
||||
<el-select :model-value="modelValue?.type ?? undefined" @update:model-value="onTypeChange"
|
||||
:clearable="!field.required" :disabled="disabled">
|
||||
<el-option v-for="tab in field.tabs" :key="tab.key" :label="vueAdmin.t(tab.label)" :value="tab.key" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
@@ -16,7 +24,7 @@
|
||||
<el-form-item :label="vueAdmin.t(childField.label)" :required="childField.required">
|
||||
<component :is="vueAdmin.getFieldComponent(moduleKey, childField.type, childField.key)"
|
||||
:field="childField"
|
||||
:model-value="innerValue[childField.key]"
|
||||
:model-value="(modelValue || {})[childField.key]"
|
||||
@update:model-value="onChildChange(childField.key, $event)"
|
||||
mode="edit"
|
||||
:disabled="disabled" />
|
||||
@@ -27,7 +35,7 @@
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { computed, inject, onMounted } from 'vue'
|
||||
import { computed, inject } from 'vue'
|
||||
import { vueAdmin } from '../../VueAdmin'
|
||||
|
||||
const props = defineProps<{
|
||||
@@ -43,39 +51,18 @@ const emit = defineEmits<{
|
||||
|
||||
const moduleKey = inject('shrimpModuleKey', '')
|
||||
|
||||
const displayText = computed(() => {
|
||||
if (!props.modelValue || typeof props.modelValue !== 'object') return '-'
|
||||
const type = props.modelValue.type
|
||||
const tab = props.field.tabs?.find((t: any) => t.key === type)
|
||||
return tab ? vueAdmin.t(tab.label) : String(type)
|
||||
})
|
||||
const selectedTab = computed(() =>
|
||||
props.field.tabs?.find((t: any) => t.key === props.modelValue?.type)
|
||||
)
|
||||
|
||||
const selectedTab = computed(() => {
|
||||
const type = props.modelValue?.type
|
||||
return props.field.tabs?.find((t: any) => t.key === type)
|
||||
})
|
||||
|
||||
const innerValue = computed(() => {
|
||||
const val = props.modelValue
|
||||
if (val != null && typeof val === 'object' && Object.keys(val).length > 0) {
|
||||
return val
|
||||
}
|
||||
return initValue()
|
||||
})
|
||||
|
||||
function initValue() {
|
||||
const firstTab = props.field.tabs?.[0]
|
||||
if (!firstTab) return {}
|
||||
const obj: any = { type: firstTab.key }
|
||||
firstTab.fields?.forEach((f: any) => {
|
||||
if (f.defaultValue !== undefined) {
|
||||
obj[f.key] = typeof f.defaultValue === 'function' ? f.defaultValue() : f.defaultValue
|
||||
}
|
||||
})
|
||||
return obj
|
||||
}
|
||||
const branchLabel = computed(() => selectedTab.value ? vueAdmin.t(selectedTab.value.label) : '')
|
||||
|
||||
function onTypeChange(type: any) {
|
||||
// 清空(非必填) → 整个 tab 置空:type=null、空状态、分支消失
|
||||
if (type == null || type === '') {
|
||||
emit('update:modelValue', null)
|
||||
return
|
||||
}
|
||||
const tab = props.field.tabs?.find((t: any) => t.key === type)
|
||||
const obj: any = { type }
|
||||
tab?.fields?.forEach((f: any) => {
|
||||
@@ -87,24 +74,32 @@ function onTypeChange(type: any) {
|
||||
}
|
||||
|
||||
function onChildChange(key: string, value: any) {
|
||||
emit('update:modelValue', { ...innerValue.value, [key]: value })
|
||||
emit('update:modelValue', { ...(props.modelValue || {}), [key]: value })
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
const val = props.modelValue
|
||||
if (val == null || val === '' || (typeof val === 'object' && Object.keys(val).length === 0)) {
|
||||
emit('update:modelValue', initValue())
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.tab-display {
|
||||
display: inline-block;
|
||||
max-width: 200px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
display: inline-flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 4px 10px;
|
||||
}
|
||||
|
||||
.tab-branch {
|
||||
font-weight: 600;
|
||||
color: var(--el-color-primary);
|
||||
}
|
||||
|
||||
.tab-child {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.tab-child-label {
|
||||
color: var(--el-text-color-secondary);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.field-tab {
|
||||
|
||||
@@ -19,7 +19,7 @@
|
||||
:model-value="modelValue"
|
||||
@update:model-value="$emit('update:modelValue', $event)"
|
||||
:disabled="disabled"
|
||||
clearable
|
||||
:clearable="!field.required"
|
||||
/>
|
||||
</template>
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@
|
||||
<div v-if="!vueAdmin.state.isMobile && nextMenu.length > 0" class="aminui-side">
|
||||
<div class="adminui-side-scroll">
|
||||
<el-scrollbar>
|
||||
<el-menu :default-active="$route.fullPath" router>
|
||||
<el-menu :default-active="$route.path" router>
|
||||
<navMenu :navMenus="nextMenu"></navMenu>
|
||||
</el-menu>
|
||||
</el-scrollbar>
|
||||
@@ -43,15 +43,18 @@
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { ref, watch } from "vue";
|
||||
import { vueAdmin } from "../VueAdmin";
|
||||
import { ref, watch, defineAsyncComponent } from "vue";
|
||||
import { vueAdmin, resolveVue } 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 Logo from "./logo.vue";
|
||||
|
||||
// 顶栏走 resolveVue,消费侧放 shrimp/components/userbar.vue 即可整体替换。
|
||||
// 其余内置组件仍是静态 import——等真有人要覆盖再逐个放开,不预先把整棵树异步化。
|
||||
const Userbar = defineAsyncComponent(resolveVue("components/userbar.vue"));
|
||||
|
||||
// 初始化选中菜单
|
||||
let currentPath = vueAdmin.router.currentRoute.value.path;
|
||||
let pick = vueAdmin.getMenuIndex(currentPath);
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
<el-main>
|
||||
<el-scrollbar>
|
||||
<el-menu
|
||||
:default-active="$route.fullPath"
|
||||
:default-active="$route.path"
|
||||
@select="select"
|
||||
router
|
||||
background-color="#212d3d"
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
//
|
||||
// 消费侧用法见 README.md。本文件只做 re-export。
|
||||
|
||||
// ===== 类型契约(IShrimpType 本地副本,@syncedFrom shrimp-server contract 1.0.0)=====
|
||||
// ===== 类型契约(IShrimpType 是 shrimp-server 那份的副本,由其 postbuild 自动同步)=====
|
||||
export {
|
||||
ShrimpCode,
|
||||
ShrimpError,
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
<template>
|
||||
<ShrimpTable :moduleKey="moduleKey" />
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
// 业务模块的内置兜底:消费侧没给 module/<key>.vue 时用这份。
|
||||
// 后端 moduleInfo 已经把字段、筛选、可用事件都声明清楚了,ShrimpTable 要的只有一个 moduleKey——
|
||||
// 所以「有个模块叫 xxx」这件事本身就够渲染出一张表,不必再让消费侧写一遍。
|
||||
// 有增量(加列插槽、换布局)时照旧写 module/<key>.vue 覆盖,后缀匹配消费侧优先。
|
||||
import ShrimpTable from '../components/ShrimpTable.vue'
|
||||
|
||||
// events 也声明出来:registerRoute 是连 events 一起当 props 传下来的,
|
||||
// 不声明它会掉进 attrs 一路透传到 ShrimpTable 的根元素上。
|
||||
defineProps<{ moduleKey: string; events?: string[] }>()
|
||||
</script>
|
||||
+17
-1
@@ -50,6 +50,7 @@
|
||||
<script lang="ts" setup>
|
||||
import { ref, onMounted } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { useRoute } from 'vue-router'
|
||||
import { vueAdmin } from '../VueAdmin'
|
||||
import { IRole, IRoleProto, WithId, ILabel } from '../IShrimpType'
|
||||
import { ElMessage } from 'element-plus'
|
||||
@@ -61,12 +62,24 @@ interface IPowerItem {
|
||||
}
|
||||
|
||||
const { t } = useI18n()
|
||||
const route = useRoute()
|
||||
|
||||
const props = defineProps<{
|
||||
moduleKey: string
|
||||
events?: string[]
|
||||
}>()
|
||||
|
||||
// relation 跳转落到 role 页时带 ?filter={"_id":...}。role 是自定义 master-detail 页(非 ShrimpTable、
|
||||
// 不做服务端过滤),全量加载后按这个 _id 在列表里选中那条;解析不出就走默认(选第一个)。
|
||||
function jumpTargetId(): string {
|
||||
try {
|
||||
const f = route.query.filter ? JSON.parse(String(route.query.filter)) : null
|
||||
return f && typeof f === 'object' ? String(f._id || '') : ''
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
const roleApi = vueAdmin.getModule<IRoleProto>('role')
|
||||
|
||||
const roleList = ref<WithId<IRole>[]>([])
|
||||
@@ -138,7 +151,10 @@ async function handleDelete() {
|
||||
onMounted(async () => {
|
||||
allPowers.value = await roleApi.allPower()
|
||||
await loadRoles()
|
||||
if (roleList.value.length > 0) {
|
||||
const jumpId = jumpTargetId()
|
||||
if (jumpId && roleList.value.some(r => r._id === jumpId)) {
|
||||
onSelect(jumpId)
|
||||
} else if (roleList.value.length > 0) {
|
||||
onSelect(roleList.value[0]._id)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -55,6 +55,11 @@ textarea {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
overflow: auto;
|
||||
/* 挂载点没加 class="aminui" 时的兜底:#app 已经是 height:100%(本文件开头),
|
||||
但它是块级容器,上面那行 flex:1 在块级父容器里不生效,布局会塌成内容高度——
|
||||
侧边栏比页面矮一截、还跟着表格异步加载忽长忽短,且不报错、页面照常打开。
|
||||
父级确实是 .aminui 时,flex:1 1 0% 接管尺寸,这行等价不冲突。 */
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
/* 全局滚动条样式 */
|
||||
|
||||
Reference in New Issue
Block a user