Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2ce6fd6d2f | ||
|
|
603e33d17f | ||
|
|
b7042c8387 | ||
|
|
bed4d4dc4a | ||
|
|
ab312fb24f | ||
|
|
546d95c926 | ||
|
|
6b0a6118e0 | ||
|
|
09ad43007a |
@@ -4,37 +4,153 @@ Shrimp 框架前端 —— 一种**经典解决方案**(不是框架本身),消
|
|||||||
|
|
||||||
如果你想换 UI 库或者换前端技术栈,直接照 shrimp-server 的约定再写一份就行,不依赖本包。
|
如果你想换 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.7.10",
|
||||||
|
|
||||||
|
// ⚠️ 不能删 —— 下面 6 个是 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"
|
||||||
|
},
|
||||||
|
"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
|
```ts
|
||||||
// main.ts
|
|
||||||
import { createApp } from 'vue'
|
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 'shrimp-admin/style'
|
||||||
|
|
||||||
|
import { createShrimpAdmin, App } from 'shrimp-admin'
|
||||||
import zhCn from './locales/zh-cn.json'
|
import zhCn from './locales/zh-cn.json'
|
||||||
import en from './locales/en.json'
|
import en from './locales/en.json'
|
||||||
|
|
||||||
const app = createApp(App)
|
const app = createApp(App)
|
||||||
app.use(createShrimpAdmin({
|
app.use(createShrimpAdmin({
|
||||||
config: {
|
config: {
|
||||||
API_URL: '/admin-api',
|
API_URL: '/admin-api', // 相对路径,由 vite proxy 转发
|
||||||
TIMEOUT: 10000,
|
TIMEOUT: 10000,
|
||||||
},
|
},
|
||||||
locales: { 'zh-cn': zhCn, en },
|
locales: { 'zh-cn': zhCn, en },
|
||||||
|
// ⚠️ import.meta.glob 必须写在消费侧的文件里(vite 静态扫描相对本文件),
|
||||||
|
// 不能封装成函数从别处调
|
||||||
sources: import.meta.glob('./shrimp/**/*.vue'),
|
sources: import.meta.glob('./shrimp/**/*.vue'),
|
||||||
}))
|
}))
|
||||||
app.mount('#app')
|
app.mount('#app')
|
||||||
```
|
```
|
||||||
|
|
||||||
## 唯一约定: `sources` 路径后缀覆盖
|
## 4. 每个业务模块一个薄壳 `src/shrimp/module/<key>.vue`
|
||||||
|
|
||||||
|
⚠️ **不能省。**后端有几个 moduleKey,这里就得有几个文件 —— 这**不是「覆盖」,是「注册」**:框架的内置兜底只兜自己的 login/layout/404,不认识你的业务模块,少一个那个菜单就点不开。
|
||||||
|
|
||||||
|
```vue
|
||||||
|
<!-- src/shrimp/module/product.vue —— 后端 moduleKey === 'product' -->
|
||||||
|
<template>
|
||||||
|
<ShrimpTable moduleKey="product" />
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
// 字段、筛选、编辑全由后端 moduleInfo 声明,ShrimpTable 自动渲染,这里不写业务代码
|
||||||
|
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']` |
|
||||||
|
| `module component not found: module/<key>.vue`,菜单点不开 | 少了业务模块薄壳 | 补 `src/shrimp/module/<key>.vue`,模板第 4 节 |
|
||||||
|
| 页面出来了但没样式,**图标巨大** | 没引 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、由消费侧安装,它的基础样式自然也该由消费侧引 —— 框架替你引会锁死版本、也挡住你换主题。顺序不能反:覆盖必须在基础之后。
|
||||||
|
|
||||||
|
## 业务模块薄壳
|
||||||
|
|
||||||
|
框架靠 `sources` 里扫到的 `module/<key>.vue` 去 `registerRoute`。它没有别的途径知道你有哪些业务模块 —— 后端 moduleInfo 只告诉它「有个 key 叫 product」,渲染成哪个组件得你指定。壳里只有一行 `<ShrimpTable>`,但这一行就是那次指定。
|
||||||
|
|
||||||
|
# 唯一约定: `sources` 路径后缀覆盖
|
||||||
|
|
||||||
消费侧把所有要交给框架的 .vue 通过单个 `sources` 入口注入(`import.meta.glob` 必须由消费侧自己调用,vite 静态扫描相对调用文件)。框架按**文件路径后缀**匹配,同后缀消费侧优先,内置兜底。
|
消费侧把所有要交给框架的 .vue 通过单个 `sources` 入口注入(`import.meta.glob` 必须由消费侧自己调用,vite 静态扫描相对调用文件)。框架按**文件路径后缀**匹配,同后缀消费侧优先,内置兜底。
|
||||||
|
|
||||||
@@ -130,7 +246,7 @@ function login() {
|
|||||||
|
|
||||||
只要文件落在 `src/shrimp/components/login.vue`,被 `sources` 的 glob 扫到,框架的 `/login` 路由就会用你这份替换内置版本。
|
只要文件落在 `src/shrimp/components/login.vue`,被 `sources` 的 glob 扫到,框架的 `/login` 路由就会用你这份替换内置版本。
|
||||||
|
|
||||||
## 消费的契约
|
# 消费的契约
|
||||||
|
|
||||||
参见 shrimp-server README `## 约定` 章节。本包消费以下条件契约:
|
参见 shrimp-server README `## 约定` 章节。本包消费以下条件契约:
|
||||||
|
|
||||||
|
|||||||
+5
-1
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "shrimp-admin",
|
"name": "shrimp-admin",
|
||||||
"version": "0.7.5",
|
"version": "0.8.1",
|
||||||
"private": true,
|
"private": true,
|
||||||
"description": "Shrimp 框架前端 — 消费 ShrimpServer + ShrimpTable 契约的经典 Vue3 + Element Plus 实现",
|
"description": "Shrimp 框架前端 — 消费 ShrimpServer + ShrimpTable 契约的经典 Vue3 + Element Plus 实现",
|
||||||
"main": "src/index.ts",
|
"main": "src/index.ts",
|
||||||
@@ -17,6 +17,10 @@
|
|||||||
"src",
|
"src",
|
||||||
"README.md"
|
"README.md"
|
||||||
],
|
],
|
||||||
|
"scripts": {
|
||||||
|
"check:contract": "node scripts/check-contract.mjs",
|
||||||
|
"sync:contract": "node scripts/check-contract.mjs --fix"
|
||||||
|
},
|
||||||
"peerDependencies": {
|
"peerDependencies": {
|
||||||
"vue": "^3.3.0",
|
"vue": "^3.3.0",
|
||||||
"vue-router": "^4.0.0",
|
"vue-router": "^4.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 定义(前端副本)
|
* 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 的逐字副本。
|
* 本文件由 shrimp-server 的 postbuild 自动同步过来,手改会被下次 build 覆盖。
|
||||||
* 不要在这里改 wire protocol,先改 shrimp-server 那份升版本,再 copy 过来更新 @syncedFrom。
|
* 手动同步: npm run sync:contract 只想看漂没漂: npm run check:contract
|
||||||
|
* 自动同步这件事存在的原因是:曾经靠人工复制,漂了一整代都没人发现——
|
||||||
|
* 副本停在旧的 json 类型、缺 object/array/fields/item/parse/refs,
|
||||||
|
* 而前端对未注册类型静默回落到 string,所以漂移不会报错、只会悄悄渲染错。
|
||||||
*
|
*
|
||||||
* 故意保留副本而不 import 'shrimp-server' 的原因:
|
* 故意保留副本而不 import 'shrimp-server' 的原因:
|
||||||
* - shrimp-server 入口会把 mongoose / express 牵进前端 bundle
|
* - shrimp-server 默认入口会把 mongoose / express 牵进前端 bundle
|
||||||
* - 拆 './types' 子入口会绕开 vite optimize、可读性也差
|
* - 前端项目不该为一份纯类型去装后端包
|
||||||
* - 类型契约低频改动,版本号对照即可
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
/** 业务错误码 */
|
/** 业务错误码 */
|
||||||
@@ -238,8 +241,9 @@ export const ShrimpFieldTypes = {
|
|||||||
Textarea: "textarea" as ShrimpFieldType,
|
Textarea: "textarea" as ShrimpFieldType,
|
||||||
Password: "password" as ShrimpFieldType,
|
Password: "password" as ShrimpFieldType,
|
||||||
Relation: "relation" as ShrimpFieldType,
|
Relation: "relation" as ShrimpFieldType,
|
||||||
Json: "json" as ShrimpFieldType,
|
|
||||||
Tab: "tab" as ShrimpFieldType,
|
Tab: "tab" as ShrimpFieldType,
|
||||||
|
Object: "object" as ShrimpFieldType,
|
||||||
|
Array: "array" as ShrimpFieldType,
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 字段可编辑状态 */
|
/** 字段可编辑状态 */
|
||||||
@@ -279,6 +283,12 @@ export interface IFieldConfig {
|
|||||||
rules?: IFieldRule[] // 通用验证规则(前后端共用)
|
rules?: IFieldRule[] // 通用验证规则(前后端共用)
|
||||||
/** tab 类型专用:每个 type 对应的子字段配置 */
|
/** tab 类型专用:每个 type 对应的子字段配置 */
|
||||||
tabs?: { key: any; label: ILabel; fields: IFieldConfig[] }[]
|
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 // 当前页码
|
page: number // 当前页码
|
||||||
pageSize: number // 每页数量
|
pageSize: number // 每页数量
|
||||||
totalPages: number // 总页数
|
totalPages: number // 总页数
|
||||||
|
refs?: Record<string, Record<string, any>> // relation 显示名字典: { moduleKey: { id: 显示名 } },前端显示时查名,替代逐行 _label
|
||||||
}
|
}
|
||||||
|
|
||||||
// ============== 数据源查询协议 ==============
|
// ============== 数据源查询协议 ==============
|
||||||
|
|||||||
+34
-1
@@ -53,6 +53,8 @@ export interface ShrimpAdminOptions {
|
|||||||
locales?: Record<string, any>
|
locales?: Record<string, any>
|
||||||
/** 语言列表,默认 [{ lang: 'zh-cn', name: '简体中文' }] */
|
/** 语言列表,默认 [{ lang: 'zh-cn', name: '简体中文' }] */
|
||||||
langList?: { lang: string; name: string }[]
|
langList?: { lang: string; name: string }[]
|
||||||
|
/** 顶栏(userbar)自定义组件,按序渲染在语言切换左侧。业务侧注入全局头部小部件(如终端商户选择器) */
|
||||||
|
headerWidgets?: Component[]
|
||||||
}
|
}
|
||||||
|
|
||||||
// ============== 源注册表 ==============
|
// ============== 源注册表 ==============
|
||||||
@@ -78,6 +80,15 @@ export function resolveVue(suffix: string): VueLoader {
|
|||||||
for (const key in internalSources) {
|
for (const key in internalSources) {
|
||||||
if (key.endsWith(tail)) return internalSources[key] as any
|
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`)
|
throw new Error(`[shrimp-admin] resolveVue: ${suffix} not found in sources`)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -88,6 +99,19 @@ export function resolveVue(suffix: string): VueLoader {
|
|||||||
|
|
||||||
const fieldRegistry = new Map<string, Component>()
|
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 {
|
function deriveFieldType(path: string): string | null {
|
||||||
const m = path.match(/\/components\/fields\/Field([A-Z][A-Za-z0-9]*)\.vue$/)
|
const m = path.match(/\/components\/fields\/Field([A-Z][A-Za-z0-9]*)\.vue$/)
|
||||||
if (!m) return null
|
if (!m) return null
|
||||||
@@ -127,7 +151,12 @@ export class VueAdmin extends ShrimpClient {
|
|||||||
moduleRoutes = new Map<string, IRouteInfo>()
|
moduleRoutes = new Map<string, IRouteInfo>()
|
||||||
|
|
||||||
getFieldComponent(_moduleKey: string, type: string, _fieldKey?: string): Component {
|
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(不可跳) */
|
/** 目标模块能否作为「单项查看」跳转目标:已按权限注册路由 且 非子模块。返回其路由信息或 undefined(不可跳) */
|
||||||
@@ -138,6 +167,9 @@ export class VueAdmin extends ShrimpClient {
|
|||||||
|
|
||||||
state = reactive({ isMobile: false })
|
state = reactive({ isMobile: false })
|
||||||
|
|
||||||
|
/** 顶栏自定义组件(由 createShrimpAdmin 的 headerWidgets 注入),userbar 按序渲染 */
|
||||||
|
headerWidgets: Component[] = []
|
||||||
|
|
||||||
private _token: string | null = null
|
private _token: string | null = null
|
||||||
get token() { return this._token }
|
get token() { return this._token }
|
||||||
set token(value: string | null) {
|
set token(value: string | null) {
|
||||||
@@ -170,6 +202,7 @@ export class VueAdmin extends ShrimpClient {
|
|||||||
super()
|
super()
|
||||||
this.config = opts.config
|
this.config = opts.config
|
||||||
this.langList = opts.langList || [{ lang: 'zh-cn', name: '简体中文' }]
|
this.langList = opts.langList || [{ lang: 'zh-cn', name: '简体中文' }]
|
||||||
|
this.headerWidgets = opts.headerWidgets || []
|
||||||
|
|
||||||
if (opts.sources) {
|
if (opts.sources) {
|
||||||
Object.assign(externalSources, opts.sources)
|
Object.assign(externalSources, opts.sources)
|
||||||
|
|||||||
@@ -4,11 +4,18 @@
|
|||||||
<el-form :model="localFilterData">
|
<el-form :model="localFilterData">
|
||||||
<template v-for="field in filterableFields" :key="field.key">
|
<template v-for="field in filterableFields" :key="field.key">
|
||||||
<el-form-item :label="vueAdmin.t(field.label)">
|
<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">
|
<slot :name="`filter-${field.key}`" :field="field" :data="localFilterData">
|
||||||
<component :is="vueAdmin.getFieldComponent(moduleKey, field.type, field.key)" :field="field"
|
<component :is="vueAdmin.getFieldComponent(moduleKey, field.type, field.key)"
|
||||||
:model-value="localFilterData[field.key]"
|
:field="field" :model-value="localFilterData[field.key]"
|
||||||
@update:model-value="onFieldChange(field.key, $event)" mode="filter" />
|
@update:model-value="onFieldChange(field.key, $event)" mode="filter" />
|
||||||
</slot>
|
</slot>
|
||||||
|
</div>
|
||||||
|
<!-- 单独清空该字段:常驻、无值时禁用(不 v-if,避免按钮显隐导致布局闪动) -->
|
||||||
|
<el-button link :icon="CircleClose" class="filter-clear"
|
||||||
|
:disabled="!hasValue(field.key)" @click="clearField(field.key)" />
|
||||||
|
</div>
|
||||||
</el-form-item>
|
</el-form-item>
|
||||||
</template>
|
</template>
|
||||||
</el-form>
|
</el-form>
|
||||||
@@ -21,6 +28,7 @@
|
|||||||
|
|
||||||
<script lang="ts" setup>
|
<script lang="ts" setup>
|
||||||
import { ref, watch } from 'vue'
|
import { ref, watch } from 'vue'
|
||||||
|
import { CircleClose } from '@element-plus/icons-vue'
|
||||||
import { IFieldConfig } from '../IShrimpType'
|
import { IFieldConfig } from '../IShrimpType'
|
||||||
import { vueAdmin } from '../VueAdmin'
|
import { vueAdmin } from '../VueAdmin'
|
||||||
|
|
||||||
@@ -68,6 +76,21 @@ function onFieldChange(key: string, value: any) {
|
|||||||
localFilterData.value = { ...localFilterData.value, [key]: value }
|
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() {
|
function handleReset() {
|
||||||
closedByReset.value = true
|
closedByReset.value = true
|
||||||
localFilterData.value = {}
|
localFilterData.value = {}
|
||||||
@@ -101,4 +124,23 @@ function handleConfirm() {
|
|||||||
.shrimp-drawer .el-drawer__body .el-form-item {
|
.shrimp-drawer .el-drawer__body .el-form-item {
|
||||||
margin-bottom: 20px;
|
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>
|
</style>
|
||||||
|
|||||||
@@ -35,7 +35,7 @@
|
|||||||
</el-table-column>
|
</el-table-column>
|
||||||
</template>
|
</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 }">
|
<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="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)" />
|
<el-button v-if="can('edit')" link type="primary" :icon="Edit" size="large" @click="handleEdit(row)" />
|
||||||
@@ -100,6 +100,8 @@ interface Props {
|
|||||||
pageSize?: number
|
pageSize?: number
|
||||||
/** 显式锁定的筛选条件(覆盖自动 ownerKey 推断);用户无法修改,会合并进 filter 并在筛选抽屉中隐藏 */
|
/** 显式锁定的筛选条件(覆盖自动 ownerKey 推断);用户无法修改,会合并进 filter 并在筛选抽屉中隐藏 */
|
||||||
baseFilter?: Record<string, any>
|
baseFilter?: Record<string, any>
|
||||||
|
/** 显式指定操作列宽度;传入后覆盖按内置按钮数量自动计算的宽度,适用于 row-actions 插槽塞了多个按钮的场景 */
|
||||||
|
rowActionsWidth?: number | string
|
||||||
}
|
}
|
||||||
|
|
||||||
const props = withDefaults(defineProps<Props>(), {
|
const props = withDefaults(defineProps<Props>(), {
|
||||||
@@ -287,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 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
|
let n = 0
|
||||||
if (hasActiveField.value && can('edit')) n++
|
if (hasActiveField.value && can('edit')) n++
|
||||||
if (can('edit')) n++
|
if (can('edit')) n++
|
||||||
|
|||||||
@@ -1,19 +1,21 @@
|
|||||||
<template>
|
<template>
|
||||||
<template v-if="mode === 'display'">
|
<template v-if="mode === 'display'">
|
||||||
<!-- 显示=前端递归渲染:分支标签 + 选中分支的子字段(各自 display 组件,relation 查 refs/可点、嵌套 tab 再递归) -->
|
<!-- 显示=前端递归渲染:分支标签 + 选中分支子字段。没选 type(清空) → 显示 - -->
|
||||||
<span v-if="!modelValue || typeof modelValue !== 'object'">-</span>
|
<span v-if="!modelValue || typeof modelValue !== 'object' || modelValue.type == null">-</span>
|
||||||
<span v-else class="tab-display">
|
<span v-else class="tab-display">
|
||||||
<span class="tab-branch">{{ branchLabel }}</span>
|
<span class="tab-branch">{{ branchLabel }}</span>
|
||||||
<span v-for="childField in selectedTab?.fields || []" :key="childField.key" class="tab-child">
|
<span v-for="childField in selectedTab?.fields || []" :key="childField.key" class="tab-child">
|
||||||
<span class="tab-child-label">{{ vueAdmin.t(childField.label) }}:</span>
|
<span class="tab-child-label">{{ vueAdmin.t(childField.label) }}:</span>
|
||||||
<component :is="vueAdmin.getFieldComponent(moduleKey, childField.type, childField.key)"
|
<component :is="vueAdmin.getFieldComponent(moduleKey, childField.type, childField.key)"
|
||||||
:field="childField" :model-value="innerValue[childField.key]" mode="display" />
|
:field="childField" :model-value="(modelValue || {})[childField.key]" mode="display" />
|
||||||
</span>
|
</span>
|
||||||
</span>
|
</span>
|
||||||
</template>
|
</template>
|
||||||
<div v-else class="field-tab">
|
<div v-else class="field-tab">
|
||||||
<el-form-item :label="vueAdmin.t(field.label) + ' - 类型'" :required="field.required">
|
<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-option v-for="tab in field.tabs" :key="tab.key" :label="vueAdmin.t(tab.label)" :value="tab.key" />
|
||||||
</el-select>
|
</el-select>
|
||||||
</el-form-item>
|
</el-form-item>
|
||||||
@@ -22,7 +24,7 @@
|
|||||||
<el-form-item :label="vueAdmin.t(childField.label)" :required="childField.required">
|
<el-form-item :label="vueAdmin.t(childField.label)" :required="childField.required">
|
||||||
<component :is="vueAdmin.getFieldComponent(moduleKey, childField.type, childField.key)"
|
<component :is="vueAdmin.getFieldComponent(moduleKey, childField.type, childField.key)"
|
||||||
:field="childField"
|
:field="childField"
|
||||||
:model-value="innerValue[childField.key]"
|
:model-value="(modelValue || {})[childField.key]"
|
||||||
@update:model-value="onChildChange(childField.key, $event)"
|
@update:model-value="onChildChange(childField.key, $event)"
|
||||||
mode="edit"
|
mode="edit"
|
||||||
:disabled="disabled" />
|
:disabled="disabled" />
|
||||||
@@ -33,7 +35,7 @@
|
|||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script lang="ts" setup>
|
<script lang="ts" setup>
|
||||||
import { computed, inject, onMounted } from 'vue'
|
import { computed, inject } from 'vue'
|
||||||
import { vueAdmin } from '../../VueAdmin'
|
import { vueAdmin } from '../../VueAdmin'
|
||||||
|
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
@@ -49,37 +51,18 @@ const emit = defineEmits<{
|
|||||||
|
|
||||||
const moduleKey = inject('shrimpModuleKey', '')
|
const moduleKey = inject('shrimpModuleKey', '')
|
||||||
|
|
||||||
const branchLabel = computed(() => {
|
const selectedTab = computed(() =>
|
||||||
const tab = selectedTab.value
|
props.field.tabs?.find((t: any) => t.key === props.modelValue?.type)
|
||||||
return tab ? vueAdmin.t(tab.label) : String(props.modelValue?.type ?? '')
|
)
|
||||||
})
|
|
||||||
|
|
||||||
const selectedTab = computed(() => {
|
const branchLabel = computed(() => selectedTab.value ? vueAdmin.t(selectedTab.value.label) : '')
|
||||||
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
|
|
||||||
}
|
|
||||||
|
|
||||||
function onTypeChange(type: any) {
|
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 tab = props.field.tabs?.find((t: any) => t.key === type)
|
||||||
const obj: any = { type }
|
const obj: any = { type }
|
||||||
tab?.fields?.forEach((f: any) => {
|
tab?.fields?.forEach((f: any) => {
|
||||||
@@ -91,15 +74,8 @@ function onTypeChange(type: any) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function onChildChange(key: string, value: 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>
|
</script>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
<template>
|
<template>
|
||||||
<div class="user-bar">
|
<div class="user-bar">
|
||||||
|
<!-- 业务侧注入的顶栏部件(headerWidgets),按序渲染在语言切换左侧 -->
|
||||||
|
<component :is="w" v-for="(w, i) in vueAdmin.headerWidgets" :key="i" />
|
||||||
<LangSwitch class="panel-item" />
|
<LangSwitch class="panel-item" />
|
||||||
<div class="panel-item" @click="screen">
|
<div class="panel-item" @click="screen">
|
||||||
<el-icon><el-icon-full-screen /></el-icon>
|
<el-icon><el-icon-full-screen /></el-icon>
|
||||||
|
|||||||
+1
-1
@@ -2,7 +2,7 @@
|
|||||||
//
|
//
|
||||||
// 消费侧用法见 README.md。本文件只做 re-export。
|
// 消费侧用法见 README.md。本文件只做 re-export。
|
||||||
|
|
||||||
// ===== 类型契约(IShrimpType 本地副本,@syncedFrom shrimp-server contract 1.0.0)=====
|
// ===== 类型契约(IShrimpType 是 shrimp-server 那份的副本,由其 postbuild 自动同步)=====
|
||||||
export {
|
export {
|
||||||
ShrimpCode,
|
ShrimpCode,
|
||||||
ShrimpError,
|
ShrimpError,
|
||||||
|
|||||||
@@ -55,6 +55,11 @@ textarea {
|
|||||||
display: flex;
|
display: flex;
|
||||||
flex: 1;
|
flex: 1;
|
||||||
overflow: auto;
|
overflow: auto;
|
||||||
|
/* 挂载点没加 class="aminui" 时的兜底:#app 已经是 height:100%(本文件开头),
|
||||||
|
但它是块级容器,上面那行 flex:1 在块级父容器里不生效,布局会塌成内容高度——
|
||||||
|
侧边栏比页面矮一截、还跟着表格异步加载忽长忽短,且不报错、页面照常打开。
|
||||||
|
父级确实是 .aminui 时,flex:1 1 0% 接管尺寸,这行等价不冲突。 */
|
||||||
|
height: 100%;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* 全局滚动条样式 */
|
/* 全局滚动条样式 */
|
||||||
|
|||||||
Reference in New Issue
Block a user