# 介绍 > 了解 Movk Nuxt 的表单、数据表格、组件和 API 集成,并选择适合 Nuxt 或 Vue + Vite 项目的接入方式。 ## 介绍 Movk Nuxt 是一套**面向 Nuxt 与 Vue 的应用开发工具包**。它基于 [Nuxt UI](https://ui.nuxt.com) 提供 AutoForm、DataTable、独立组件和组合式函数。你可以从一个组件开始,也可以组合表单、表格和主题。在 Nuxt 中,还可以统一处理 API 请求、认证和文件传输。 它提供**两种使用方式**: - **Nuxt 4** —— 获得包括 API 集成(认证、进度追踪)在内的完整能力。 - **纯 Vue + Vite** —— 经 `@movk/nuxt/vite` + `@movk/nuxt/vue-plugin`,使用其 UI 层:独立组件、AutoForm、DataTable、主题与非服务端 Composables。**API 集成域依赖 Nuxt 服务端运行时,仅 Nuxt 模式可用。** > [!NOTE] > > 遵循 > > 渐进式采用 > > 原则——你可以只用它的日期处理工具或 UI 组件,使用全自动化的 > > AutoForm > > ,在 Nuxt 中接入 > > API System > > ,或在纯 Vue + Vite 项目中引入其 UI 层(详见 > > Vue / Vite > > )。 ## 核心特性 **Schema 驱动表单 · Nuxt / Vue+Vite** AutoForm 通过 Zod Schema 自动生成完整表单界面,一份 Schema 同时定义数据结构、验证规则与 UI 配置。 **类型安全表格 · Nuxt / Vue+Vite** DataTable 提供数据/选择/索引/展开/操作等列类型,支持排序、列锁定、树形数据、分页与加载更多。 **独立组件与工具 · Nuxt / Vue+Vite** DatePicker 、 SearchForm 、 Tree 、 MessageBox 等组件与 useDateFormatter 、 useTheme 、 useMessageBox 等 composables,均可独立使用。 **API 集成系统 · 仅 Nuxt** useApiFetch 系列封装多端点、自动认证、业务状态码检查与 Toast 提示,并提供带进度的上传/下载(依赖 Nuxt 服务端运行时)。 ## 架构分层 Movk Nuxt 采用清晰的分层架构: > [!NOTE] > > **架构层级** > > - **Core Systems** - AutoForm(Schema 驱动表单)、DataTable(类型安全表格) > - **API System** - useApiFetch、useLazyApiFetch、useClientApiFetch、useUploadWithProgress、useDownloadWithProgress > - **Standalone Components** - DatePicker、SearchForm、Tree、MessageBox、ThemePicker > - **Composables** - useDateFormatter、useAutoForm、useTheme、useMessageBox 等通用组合式函数 > - **Vite/Vue 兼容层** - `@movk/nuxt/vite` + `@movk/nuxt/vue-plugin`,让上述 UI 层(Core Systems、Standalone Components、非服务端 Composables)在纯 Vue + Vite 可用(不含 API System) > - **Foundation** - 基于 [Nuxt UI](https://ui.nuxt.com)、[Zod v4](https://zod.dev)、[VueUse](https://vueuse.org) ## 核心模块 ### AutoForm - Schema 驱动的表单系统 基于 Zod Schema 的「定义即渲染」表单解决方案,支持多种控件类型、布局系统、依赖联动等高级特性。 > [!TIP] > See: /docs/auto-form/quickstart > > 深入了解 AutoForm 的核心概念和使用方法 ### DataTable - 类型安全的数据表格 基于 `@tanstack/vue-table` 的声明式列配置表格,支持数据/选择/索引/展开/操作等列类型,以及排序、列锁定、拖拽列宽、树形数据、分页与加载更多。 > [!TIP] > See: /docs/data-table > > 了解 DataTable 的列配置与高级特性 ### API System - 统一的请求与认证 提供完整的 API 请求方案: - `useApiFetch` - 基于 useFetch 封装,支持自动认证、业务状态码检查、Toast 提示 - `useUploadWithProgress` / `useDownloadWithProgress` - 带进度监控的文件上传下载 > [!TIP] > See: /docs/api > > 了解 API System 的使用方法 ### 独立组件 - 开箱即用 无需依赖 AutoForm,可直接使用的高质量 UI 组件: - `DatePicker` - 基于国际化标准的日期选择器(单选/范围/多选) - `Tree` - 支持勾选、搜索、懒加载的树形组件 - `MessageBox` - 命令式确认/提示对话框 > [!TIP] > See: /docs/components/date-picker > > 浏览所有可用组件 ### 通用工具函数 - `useDateFormatter` - 日期格式化、解析、范围处理工具 - `useAutoForm` - AutoForm 的核心逻辑封装 - `useTheme` - 主题状态读写与 CSS/配置导出 - `useMessageBox` - 命令式 alert / confirm 弹窗 > [!TIP] > See: /docs/auto-form/use-auto-form > > 查看所有 Composables # 安装 > 在 Nuxt 4 项目中安装和配置 Movk Nuxt 模块。 > [!NOTE] > See: /docs/getting-started/vue > > 在 > > Vue + Vite > > (非 Nuxt)项目中使用?请看 Vue / Vite 模式说明。 ## 环境要求 > [!NOTE] > > - **Node.js** - `^22.22.3 || ^24.15.0 || >=26.0.0` > - **Nuxt** - `^4.6.4`(需要 Nuxt 4) > - **Nuxt UI** - `>=4.13.0` > - **包管理器** - pnpm / npm / yarn ## 使用模版 使用 [Movk Nuxt Starter](https://github.com/mhaibaraai/movk-nuxt-starter) 模版快速创建一个已集成 `@movk/nuxt` 的 Nuxt 4 项目。 ```bash npm create nuxt@latest -- -t gh:mhaibaraai/movk-nuxt-starter ``` > [!TIP] > See: https://github.com/new?template_name=movk-nuxt-starter&template_owner=mhaibaraai > > 也可以在 GitHub 上点击 > > Use this template > > 直接基于模版创建仓库。 ## 添加到 Nuxt 项目 ### 安装所需依赖 > [!WARNING] > > Movk Nuxt > > 依赖 > > @nuxt/ui > > 和 > > zod > > ,请确保已安装。 > [!WARNING] > > 如果你使用的是 pnpm : > > - 请确保你在 `.npmrc` 文件中设置 `shamefully-hoist=true` > - 或者在项目的根目录中安装 `tailwindcss` ```bash [pnpm] pnpm add @movk/nuxt @nuxt/ui zod tailwindcss ``` ```bash [npm] npm install @movk/nuxt @nuxt/ui zod tailwindcss ``` ```bash [yarn] yarn add @movk/nuxt @nuxt/ui zod tailwindcss ``` ### 模块配置 在 `nuxt.config.ts` 中注册模块: ```diff [nuxt.config.ts] export default defineNuxtConfig({ + modules: ['@movk/nuxt'] }) ``` ### 引入样式 在项目的 CSS 入口中引入模块样式,并在 `nuxt.config.ts` 的 `css` 中注册该文件: ```css [app/assets/css/main.css] @import "tailwindcss"; @import "@movk/nuxt"; ``` ```diff [nuxt.config.ts] export default defineNuxtConfig({ modules: ['@movk/nuxt'], + css: ['~/assets/css/main.css'] }) ``` > [!NOTE] > > @movk/nuxt > > 内部已引入 > > @nuxt/ui > > ,无需再单独 > > @import "@nuxt/ui" > > 。整个项目应只有这一个 Tailwind 入口:多写一处 > > @import "tailwindcss" > > 会形成第二个 Tailwind 上下文,其默认主题变量会覆盖模块注入的 > > --font-sans > > 等值。 ### 安装图标集 组件图标取自 Iconify 的 `lucide` 图标集。装上对应的 `@iconify-json` 包,模块会在构建期把组件用到的图标内联进产物;不装则改为运行时向 Iconify API 按需请求,内网或离线环境会拿不到图标。 ```bash [pnpm] pnpm add -D @iconify-json/lucide ``` ```bash [npm] npm install -D @iconify-json/lucide ``` ```bash [yarn] yarn add -D @iconify-json/lucide ``` 模块只负责自己组件用到的图标,项目自己写的图标名需开启扫描才会一并入包: ```ts [nuxt.config.ts] export default defineNuxtConfig({ icon: { clientBundle: { scan: { globInclude: ['**/*.{vue,jsx,tsx,ts,md,mdc,mdx,yml,yaml}'] } } } }) ``` > [!NOTE] > > @nuxt/icon > > 默认的 > > globInclude > > 不含 > > .ts > > ,写在 composable、常量文件里的图标名会漏扫,故此处显式补上 > > ts > > 。 ## 可选配置 ```ts [nuxt.config.ts] export default defineNuxtConfig({ modules: ['@movk/nuxt'], movk: { // 组件前缀 (默认: 'M') prefix: 'M' } }) ``` ## TypeScript 支持 Movk Nuxt 提供完整的 TypeScript 类型定义,安装后自动注入到项目中。 ```ts import type { z } from 'zod' const { afz } = useAutoForm() const schema = afz.object({ email: afz.email(), // ✅ 完整的类型提示 age: afz.number() }) // 从 schema 推断数据类型 type FormData = z.output ``` ## Zod v4 集成 Movk Nuxt 使用 **Zod v4**,它引入了一些重要的 API 变更: ```ts [✅ 正确用法 (Zod v4)] import { z } from 'zod' // 使用专用验证函数 const emailSchema = z.email() const urlSchema = z.url() const uuidSchema = z.uuid() const datetimeSchema = z.iso.datetime() ``` ```ts [❌ 已废弃 (Zod v3)] import { z } from 'zod' // 不要使用旧的字符串验证方法 const emailSchema = z.string().email() const urlSchema = z.string().url() const uuidSchema = z.string().uuid() ``` > [!TIP] > See: https://zod.dev/api > > 查看 Zod 官方文档了解更多 v4 变更 # 模块配置 > 配置组件前缀、主题颜色、字体、API 端点、认证策略、响应解析规则和 Toast 提示行为。 ## 介绍 Movk Nuxt 使用 `movk` 作为配置键,在 `nuxt.config.ts` 中进行配置: ## `Prefix` - **类型**: `string` - **默认值**: `'M'` 组件前缀,用于避免与其他组件库的命名冲突。 ```ts [nuxt.config.ts] export default defineNuxtConfig({ movk: { prefix: 'My' // 组件变为 MyAutoForm, MyDatePicker 等 } }) ``` ## `Theme` 主题模块统一管理颜色、圆角、图标集与字体。前三者向 `ThemePicker` 组件、`useTheme` composable 提供可选项,字体则在构建期注入。所有字段都在 `movk.theme` 下配置。 > [!NOTE] > See: /docs/getting-started/theme > > 主题系统的运行时能力(动态切换、CSS 导出)见主题文档;交互式调参见 > > ThemePicker > > 组件。 ```ts [nuxt.config.ts] export default defineNuxtConfig({ movk: { theme: { enabled: true } } }) ``` **enabled** (`boolean`): 是否启用主题模块(appConfig 默认值、theme plugin、ThemePicker 组件注册)。默认 true。关闭后 ThemePicker 不再注册。 **colors** (`string[]`): 组件可用的颜色别名列表,透传给 @nuxt/ui 的 theme.colors。默认 ['primary', 'secondary', 'success', 'info', 'warning', 'error']。 **defaultVariants** (`object`): 组件默认变体,透传给 @nuxt/ui 的 theme.defaultVariants。 **prefix** (`string`): Tailwind CSS 工具类前缀,透传给 @nuxt/ui 的 theme.prefix。例如 'tw'。 **font** (`string | ThemeFontOption`): 全局字体。内置字体给名字即可('Alibaba PuHuiTi'、'OPPO Sans'),模块在构建期注入样式表、preconnect 与带中文回退栈的 --font-sans;自托管字体用 { name, href } 形式补上入口 CSS 地址。缺省时不注入 --font-sans,字体由项目 CSS 的 @theme 决定。字体名称,须与样式表中 @font-face 声明的 font-family 逐字一致。字体入口 CSS 的地址。例如 '/fonts/my-font.css'。内置字体可省略。既非内置、又没提供该字段的字体不会产生任何请求。 **radius** (`number`): 默认圆角(单位 rem)。缺省时不注入 --ui-radius,沿用 @nuxt/ui 的默认值或项目 CSS 的声明。例如 0.5。 **radiuses** (`number[]`): ThemePicker 圆角可选项(单位 rem)。默认 [0, 0.125, 0.25, 0.375, 0.5]。 **neutralColors** (`string[]`): ThemePicker neutral 颜色可选项。 ### 自定义字体 ```ts [nuxt.config.ts] export default defineNuxtConfig({ movk: { theme: { // 内置字体给名字即可 font: 'Alibaba PuHuiTi' // 自托管字体补上入口 CSS 地址 // font: { name: 'My Font', href: '/fonts/my-font.css' } } } }) ``` ## `Icon` 控制模块自有图标是否进入 `@nuxt/icon` 的构建期图标包。 ```ts [nuxt.config.ts] export default defineNuxtConfig({ movk: { icon: { clientBundle: true } } }) ``` **clientBundle** (`boolean`): 是否把 movk 组件与内置图标集用到的图标注入构建期图标包。默认 true。关闭后这些图标改为运行时按需请求。 > [!NOTE] > See: /docs/getting-started/theme > > 图标集切换与 > > @iconify-json/* > > 的安装说明见主题文档 · 图标集。 ## API API 系统提供完整的请求封装和认证管理,通过 `api` 选项配置。 > [!NOTE] > See: /docs/api > > API 系统的完整使用方法请参考 API 文档。 ### 基础配置 ```ts [nuxt.config.ts] export default defineNuxtConfig({ movk: { api: { // 是否启用 API 功能 enabled: true, // 默认使用的端点名称 defaultEndpoint: 'default', // 是否启用调试模式 debug: false } } }) ``` **enabled** (`boolean`): 是否启用 API 功能。默认 true。 **defaultEndpoint** (`string`): 默认使用的端点名称。默认 'default'。 **debug** (`boolean`): 是否启用调试模式,开启后会在控制台输出请求日志。默认 false。 ### `endpoints` 支持配置多个 API 端点,每个端点可以有独立的配置: ```ts [nuxt.config.ts] export default defineNuxtConfig({ movk: { api: { endpoints: { // 默认端点 default: { baseURL: '/api' }, // 管理端点 admin: { baseURL: '/admin-api', auth: { tokenType: 'Bearer' } }, // 第三方 API external: { baseURL: 'https://api.example.com', // 仅服务端注入 headers: { 'X-Secret-Key': process.env.EXTERNAL_SECRET_KEY }, // 两端均注入 publicHeaders: { 'X-Api-Version': '2' } } } } } }) ``` #### 端点选项 **baseURL** (`string`) *required*: 端点的基础 URL。 **alias** (`string`): 端点别名。 **headers** (`Record`): 该端点的默认请求头 仅服务端使用,不会暴露给客户端。 **publicHeaders** (`Record`): 该端点的公开请求头,会进入 public runtimeConfig,服务端与客户端均注入。同名键由 headers 覆盖。仅用于非机密固定头。 **auth** (`Partial`): 该端点的认证配置,会与全局配置合并。 **toast** (`Partial`): 该端点的 Toast 配置,会与全局配置合并。 **response** (`Partial`): 该端点的响应配置,会与全局配置合并。 ### `auth` 配置自动认证行为,与 `nuxt-auth-utils` 集成: > [!NOTE] > > 当 `auth.enabled` 为 `true` 且 `tokenSource` 为 `'session'` 时,模块会自动注册 `nuxt-auth-utils`。单独使用 `useUserSession` 时,请在 `modules` 中添加 `nuxt-auth-utils`。 > > 使用 `nuxt-auth-utils` v0.6 时,请在生产环境设置至少 32 个字符的 `NUXT_APP_SECRET`,可用 `openssl rand -base64 32` 生成。开发模式下,Nuxt 会在缺少该变量时生成密钥。 > > 从 v0.5 升级时,请移除旧的 `NUXT_SESSION_PASSWORD` 和 `runtimeConfig.session.password`。升级后,已登录用户需要重新登录一次。[迁移指南](https://nuxt.com/modules/auth-utils#migrate-from-v05) ```ts [nuxt.config.ts] export default defineNuxtConfig({ movk: { api: { auth: { // 启用认证 enabled: true, // Token 来源 tokenSource: 'session', // Session 中 token 的路径 sessionTokenPath: 'user.accessToken', // Token 类型 tokenType: 'Bearer', // 请求头名称 headerName: 'Authorization', // 401 未授权处理配置 unauthorized: { // 401 时跳转登录页 redirect: true, loginPath: '/login', // 401 时清除 session clearSession: true } } } } }) ``` 浏览器直连第三方 API 时,把凭据放进 `runtimeConfig.public` 并指向它: ```ts [nuxt.config.ts] export default defineNuxtConfig({ runtimeConfig: { public: { llmApiKey: '' } }, movk: { api: { auth: { enabled: true, tokenSource: 'public-runtime-config', tokenPath: 'llmApiKey', tokenType: 'Bearer', unauthorized: { redirect: false } } } } }) ``` ```bash [.env] NUXT_PUBLIC_LLM_API_KEY=your-api-key ``` > [!WARNING] > > public-runtime-config > > 与 > > publicHeaders > > 的取值都会随页面下发到浏览器,任何访问者都能读取。仅在凭据本身设计为公开、或作用域已收窄到可接受时使用;账户级密钥请走服务端代理。 #### 认证选项 **enabled** (`boolean`): 是否启用认证。默认 false。 **tokenSource** (`'session' | 'public-runtime-config'`): Token 来源。'session' 从 nuxt-auth-utils 的 session 中获取;'public-runtime-config' 从 runtimeConfig.public 中获取,用于凭据本就需要在浏览器暴露的场景。默认 'session'。 **sessionTokenPath** (`string`): Session 中 token 的路径。例如 'token' 对应 session.token,'user.token' 对应 session.user.token。默认 'token'。 **tokenPath** (`string`): runtimeConfig.public 中 token 的路径,支持点号嵌套。仅当 tokenSource 为 'public-runtime-config' 时生效。默认 'apiToken'。 **tokenType** (`'Bearer' | 'Basic' | 'Custom'`): Token 类型。默认 'Bearer'。 **customTokenType** (`string`): 自定义 Token 类型值,当 tokenType 为 'Custom' 时使用。 **headerName** (`string`): 请求头名称。默认 'Authorization'。 **unauthorized** (`ApiUnauthorizedConfig`): 401 未授权处理配置。401 错误时是否自动跳转登录页。默认 true。登录页路径。默认 '/login'。401 错误时是否自动清除 session。默认 true。 ### `response` 配置 API 响应的解析规则,包括业务状态码判断、数据解包字段和消息提取: ```ts [nuxt.config.ts] export default defineNuxtConfig({ movk: { api: { response: { // 成功状态码列表 successCodes: [200, 0], // 状态码字段名 codeKey: 'code', // 消息字段名 messageKey: 'message', // 数据字段名 dataKey: 'data', // 是否校验业务状态码 businessCheck: true, // 是否按 dataKey 解包 unwrap: true } } } }) ``` 端点级 `response` 覆盖全局。直接返回数组或裸对象的端点关闭校验与解包,请求级 `businessCheck` / `unwrap` 显式值仍可覆盖: ```ts [nuxt.config.ts] export default defineNuxtConfig({ movk: { api: { endpoints: { sensor: { baseURL: 'https://sensor.example.com', response: { businessCheck: false, unwrap: false } } } } } }) ``` #### 响应配置选项 **successCodes** (`(number | string)[]`): 成功状态码列表,响应中的 code 值在此列表中视为成功。默认 [200, 0]。 **codeKey** (`string`): 响应中状态码的字段名。默认 'code'。 **messageKey** (`string`): 响应中消息的字段名。默认 'message'。 **dataKey** (`string`): 响应中数据的字段名。默认 'data'。 **businessCheck** (`boolean`): 是否按 successCodes 校验业务状态码,关闭后任何 2xx 响应都视为成功。默认 true。 **unwrap** (`boolean`): 是否按 dataKey 解包业务数据,关闭后调用方拿到原始响应体。默认 true。 ### `toast` 配置全局 Toast 提示行为: ```ts [nuxt.config.ts] export default defineNuxtConfig({ movk: { api: { toast: { // 全局启用提示 enabled: true, // 成功提示配置 success: { show: true, color: 'success', duration: 3000, // 仅变更类请求弹出成功提示,GET 保持安静 methods: ['POST', 'PUT', 'PATCH', 'DELETE'] }, // 错误提示配置 error: { show: true, color: 'error', duration: 3000 } } } } }) ``` #### Toast 选项 **enabled** (`boolean`): 是否全局启用提示。默认 true。 **success** (`Partial & { show?: boolean, methods?: string[] }`): 成功提示配置。show: false 关闭成功提示;methods 限定仅在这些 HTTP 方法上提示(大小写不敏感),未声明表示不限制。 **error** (`Partial & { show?: boolean, methods?: string[] }`): 错误提示配置。show: false 关闭错误提示;methods 同上,通常保持不声明让所有方法都能看到错误。 > [!NOTE] > > enabled > > 、 > > show > > 、 > > methods > > 均为全局层开关,请求级可单次覆盖。优先级为请求级 > > show > > 显式声明 > 请求级 > > successMessage > > / > > errorMessage > > > 全局 > > success.show > > / > > error.show > > / > > methods > > > 全局 > > enabled > > 。即全局关闭或方法未命中白名单时,请求级传 > > toast: { success: { show: true } } > > 或 > > toast: { successMessage: '保存成功' } > > 都会弹出。 > [!TIP] > > methods > > 只能写在全局或端点配置里;单个请求只有一个方法,请求级 > > toast > > 不接受该字段。端点级 > > methods > > 整体覆盖全局,不做数组合并。 ## 配置优先级 配置按以下优先级合并(后者覆盖前者): 1. **模块内置默认值** - `api-defaults.ts` 中定义的默认配置 2. **全局配置** - `movk.api.auth`、`movk.api.toast`、`movk.api.response` 3. **端点配置** - `movk.api.endpoints[name].auth` 等 4. **请求级配置** - `useApiFetch` 的 `toast` 选项等 ```ts // 示例:请求级配置覆盖全局配置 const { data } = await useApiFetch('/users', { toast: { successMessage: '获取成功', // 覆盖全局配置 error: false // 禁用错误提示 } }) ``` 请求头按以下顺序叠加(后者覆盖前者): 1. **端点 `publicHeaders`** - 服务端与客户端均注入 2. **端点 `headers`** - 仅服务端注入,覆盖同名 `publicHeaders` 3. **请求级 `headers`** - 调用 `$api` 或 `useApiFetch` 时传入 4. **auth 注入** - `onRequest` 拦截器按 `headerName` 写入,优先级最高 ## 组件与校验本地化 通过 `UApp` 设置组件语言。用 `extendMovkLocale(locale, overrides)` 覆盖个别文案,用 `useMovkLocale()` 读取当前语言和翻译函数。 ```ts [nuxt.config.ts] export default defineNuxtConfig({ movk: { zod: { locale: 'auto', fallback: 'en', locales: ['en', 'zh-CN'] } } }) ``` `movk.zod` 配置校验语言与必填提示。`auto` 让 AutoForm 和 SearchForm 在客户端跟随 UApp,服务端使用 `fallback`。在 `movk:zod:config` 钩子设置 `customError`,可覆盖当前 Nuxt 应用内这两个表单的提示。Vue + Vite 在注册 Vue 插件时传入 `{ zod: { customError } }`。直接调用 Zod 时使用全局固定语言或 `fallback`。 ## 环境变量 对于敏感配置(如 API 密钥),建议使用环境变量: ```ts [nuxt.config.ts] export default defineNuxtConfig({ movk: { api: { endpoints: { external: { baseURL: process.env.EXTERNAL_API_URL, headers: { 'X-API-Key': process.env.EXTERNAL_API_KEY } } } } } }) ``` ```bash [.env] EXTERNAL_API_URL=https://api.example.com EXTERNAL_API_KEY=your-api-key ``` > [!WARNING] > > 不要将敏感信息(如 API 密钥、密码)直接写在配置文件中,始终使用环境变量。 # Vue / Vite > 在纯 Vue + Vite 项目中使用 Movk 的独立组件、主题与 Composables,无需 Nuxt。 > [!NOTE] > See: /docs/getting-started/installation > > 使用 > > Nuxt > > ?请看 Nuxt 模式的安装说明。 `@movk/nuxt` 不仅是 Nuxt 模块,还提供 Vite 插件(`@movk/nuxt/vite`)与 Vue 插件(`@movk/nuxt/vue-plugin`),让独立 UI 组件、AutoForm / DataTable、主题与非服务端 Composables 在纯 Vue + Vite 项目中直接可用。 > [!WARNING] > > Vue / Vite 模式 > > 不包含 API 集成域 > > ( > > useApiFetch > > / > > useLazyApiFetch > > / > > useClientApiFetch > > 、上传下载、 > > $api > > 插件、鉴权与错误 toast 等),它们依赖 Nuxt 服务端运行时,仅在 Nuxt 模式下可用。 ## 安装 ### 安装依赖 需要 `@nuxt/ui >=4.13.0`。 ```bash [pnpm] pnpm add @movk/nuxt @nuxt/ui zod tailwindcss ``` ```bash [npm] npm install @movk/nuxt @nuxt/ui zod tailwindcss ``` ```bash [yarn] yarn add @movk/nuxt @nuxt/ui zod tailwindcss ``` vue-router 默认启用(`ui.router` 选项控制)。若使用默认值,请同时安装 `vue-router`: ```bash [pnpm] pnpm add vue-router ``` ```bash [npm] npm install vue-router ``` ### 添加 Vite 插件 在 `vite.config.ts` 注册 `movk()` 插件: ```ts [vite.config.ts (Vite)] import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import movk from '@movk/nuxt/vite' export default defineConfig({ plugins: [ vue(), movk() ] }) ``` ```ts [vite.config.ts (Inertia)] import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import movk from '@movk/nuxt/vite' export default defineConfig({ plugins: [ vue(), movk({ ui: { router: 'inertia' } }) ] }) ``` > [!TIP] > > `movk()` 内部注册了 `unplugin-auto-import` 与 `unplugin-vue-components`,会生成 `auto-imports.d.ts` 与 `components.d.ts`。建议将它们加入 `.gitignore` 并在 `tsconfig` 中 include。 > > ```json [tsconfig.app.json] > { > "include": ["src/**/*.ts", "src/**/*.vue", "auto-imports.d.ts", "components.d.ts"] > } > ``` > > ```bash [.gitignore] > auto-imports.d.ts > components.d.ts > ``` > [!TIP] > > 若使用 TypeScript,可在 `tsconfig` 中为主题虚拟模块添加别名,以在 `vite.config.ts` 获得补全: > > ```json [tsconfig.node.json] > { > "compilerOptions": { > "paths": { > "#build/movk-ui": ["./node_modules/.movk-ui/movk-ui"], > "#build/ui": ["./node_modules/.nuxt-ui/ui"] > } > } > } > ``` ### 注册 Vue 插件 在入口注册 `@movk/nuxt/vue-plugin`(内部已链入 `@nuxt/ui/vue-plugin`): ```ts [src/main.ts] import './assets/css/main.css' import { createApp } from 'vue' import { createRouter, createWebHistory } from 'vue-router' import movk from '@movk/nuxt/vue-plugin' import App from './App.vue' const router = createRouter({ routes: [], history: createWebHistory() }) createApp(App) .use(router) .use(movk) .mount('#app') ``` ### 引入样式 ```css [src/assets/css/main.css] @import "tailwindcss"; @import "@movk/nuxt"; ``` ### 用 `` 包裹根组件 `` 提供 Toast、Tooltip 与命令式 overlay 的全局上下文,`useMessageBox` 依赖它: ```vue [src/App.vue] ``` > [!NOTE] > > 根容器建议加 > > class="isolate" > > ( > > index.html > > 的 > > #app > > ),确保样式作用域与 overlay 层叠正确。 ## 与 UnoCSS / 已有全局样式共存 在已有项目中接入时,常见的问题是 Nuxt UI 组件的背景、内边距、圆角等样式不生效。原因在于级联层:Tailwind 的工具类位于 `@layer utilities`,而**任何未分层的样式都会压过 `@layer` 内的样式,与选择器优先级无关**。UnoCSS 默认输出的 preflight(reset)以及项目自带的全局 reset 都属于未分层样式。 > [!TIP] > > 在浏览器 DevTools 的「样式」面板中,没有标注「级联层」的规则就是未分层样式。dev 模式下检测到 UnoCSS 输出未分层的 reset 时, > > movk() > > 会在终端给出警告。 ### 关闭 UnoCSS 的 reset `@import "tailwindcss"` 已在 `@layer base` 中提供等价的 reset,直接关闭 UnoCSS 的 reset 即可: ```ts [uno.config.ts] import { defineConfig, presetWind4 } from 'unocss' export default defineConfig({ presets: [ presetWind4({ preflights: { reset: false } }) ] }) ``` > [!WARNING] > > presetWind4 > > 的开关是 > > preflights.reset > > ,写成顶层的 > > reset: false > > 不会生效。 ### 把 UnoCSS 的 preflight 归入 base 层 如果需要保留 UnoCSS 的 preflight,可以用 `outputToCssLayers` 把它放进 Tailwind 的 `base` 层,工具类则保持未分层: ```ts [uno.config.ts] export default defineConfig({ outputToCssLayers: { cssLayerName: layer => layer === 'preflights' ? 'base' : null } }) ``` > [!NOTE] > > 不建议把 UnoCSS 的工具类也放进 layer:项目里如果还有 Element Plus 等未分层的组件库样式,分层后的工具类会输给它们,原本用工具类覆盖组件库样式的写法会失效。 ### 把已有的全局 reset 放进 base 层 项目自带的 reset 用 `@layer base` 包裹后,就不会覆盖 Nuxt UI 的工具类: ```css [src/styles/reset.css] @layer base { *, ::before, ::after { margin: 0; padding: 0; } } ``` ## 选项 在 `vite.config.ts` 的 `movk()` 中传入选项进行配置。 ### `prefix` 组件前缀 组件名前缀。 - 默认:`M` ```ts [vite.config.ts] movk({ prefix: 'M' }) ``` ### `site` 站点信息 站点名称,影响主题持久化的 localStorage key 前缀(`-ui-*`)。 ```ts [vite.config.ts] movk({ site: { name: 'my-app' } }) ``` ### `theme` 主题 `theme.colors`(颜色别名)、`theme.defaultVariants`(默认变体)、`theme.prefix`(与 Tailwind 前缀一致)、`theme.font`(字体)等,对齐 Nuxt 模式 `movk.theme`。`font` 与 Nuxt 模式行为一致:构建期把字体样式表的 `` 注入 `index.html`(`vite dev`/`vite build` 均生效),并写入 `--font-sans`,详见 [主题系统 · 字体](https://nuxt.mhaibaraai.me/docs/getting-started/theme#%E5%AD%97%E4%BD%93)。 ```ts [vite.config.ts] movk({ theme: { defaultVariants: { color: 'neutral', size: 'sm' } } }) ``` ### `icon` 图标 `icon.clientBundle` 控制 movk 组件与内置图标集用到的图标是否进入构建期图标包,对齐 Nuxt 模式 `movk.icon`。图标数据需要项目安装对应的 `@iconify-json/*` 包,未安装的图标集会被自动跳过(不会导致构建失败),详见 [主题系统 · 图标集](https://nuxt.mhaibaraai.me/docs/getting-started/theme#%E5%9B%BE%E6%A0%87%E9%9B%86)。 ```ts [vite.config.ts] movk({ icon: { clientBundle: false } }) ``` ### `ui` `ui` 是 `@nuxt/ui` unplugin 配置(`Partial`)的透传口,承载 `router`、`colorMode`、`autoImport`、`components`、`dts`、`icon`、`ui` 主题等。movk 会把自身 composables 与组件解析自动注入 `ui.autoImport` / `ui.components` / `ui.icon.clientBundle.icons`,无需手动配置即可使用。 > [!NOTE] > See: https://ui.nuxt.com/docs/getting-started/installation/vue#options > > 查看 Nuxt UI 模块文档 了解 > > ui > > 选项的完整配置与功能。 # 主题系统 > 通过模块默认值、ThemePicker 组件和 useTheme composable 管理颜色、圆角、图标集与深色模式,字体则在构建期配置。 ## 介绍 Movk Nuxt 在 [Nuxt UI](https://ui.nuxt.com) 主题之上提供统一的运行时主题管理:颜色、圆角、字体、图标集与深色模式集中由一处控制,并可在运行时交互式调整、一键导出 CSS 变量或配置代码。 主题能力由三部分组成: - **[模块默认值](https://nuxt.mhaibaraai.me/docs/getting-started/configuration)** : 在 `nuxt.config.ts` 的 `movk.theme` 中声明可选项。 - **`ThemePicker` 组件** : 面向用户的可视化调参面板,支持导出。 - **`useTheme` composable** : 在脚本中读写主题状态、导出 CSS/配置。 ## 启用与关闭 主题模块默认启用。关闭后不再注入 `appConfig` 默认值、theme 插件与 `ThemePicker` 组件: ```ts [nuxt.config.ts] export default defineNuxtConfig({ movk: { theme: { enabled: false } } }) ``` ## ThemePicker 组件 `ThemePicker` 提供颜色、圆角、图标集、深色模式的可视化切换,并能导出当前主题。 > [!TIP] > See: #themepicker-参考 > > 查看 ThemePicker 的完整 props、事件与用法。 ## useTheme `useTheme` 暴露主题的响应式状态与导出方法,适合自定义主题面板或在业务逻辑中读取主题: ```ts const { color, neutral, radius, icon, mode, exportCSS, exportConfig, resetTheme } = useTheme() // 读取/切换主题 color.value = 'green' mode.value = 'dark' // 导出当前主题 const css = exportCSS() const config = exportConfig() ``` > [!TIP] > See: #usetheme-参考 > > 查看 useTheme 返回的全部状态与方法。 ## 字体 字体是构建期配置,不随运行时切换。声明一行即可: ```ts [nuxt.config.ts] export default defineNuxtConfig({ movk: { theme: { font: 'Alibaba PuHuiTi' } } }) ``` 模块在构建期完成三件事,不依赖运行时 JS——Nuxt 模式随 SSR `` 直出,Vue/Vite 模式随构建产物 `index.html` 直出(`vite dev`/`vite build` 均生效): - 向 `` 写入字体样式表的 `` - 为跨域字体补一条带 `crossorigin` 的 `preconnect` - 注入 `@theme { --font-sans }`,首选字体之后附上覆盖 macOS、Windows 与 Linux 的系统中文字体回退栈 内置字体托管在 [movk-fonts](https://cdn.mhaibaraai.me),取值必须与其 `@font-face` 声明的 `font-family` 逐字一致: | 取值 | 样式表 | | --- | --- | | `Alibaba PuHuiTi` | `https://cdn.mhaibaraai.me/fonts/alibaba-puhuiti.css` | | `OPPO Sans` | `https://cdn.mhaibaraai.me/fonts/oppo-sans.css` | 自托管字体用 `{ name, href }` 形式补上入口 CSS 地址: ```ts [nuxt.config.ts] export default defineNuxtConfig({ movk: { theme: { font: { name: 'My Font', href: '/fonts/my-font.css' } } } }) ``` > [!WARNING] > > name > > 写错不会报错,只会静默回退到系统字体——CSS 家族名匹配对大小写不敏感,但 > > alibaba-puhuiti > > 与 > > Alibaba PuHuiTi > > 是两个不同的名字。既非内置、又没提供 > > href > > 的字体不会产生任何请求,模块会在开发期发出警告。 模块注入的 `@theme` 随 `@import "@movk/nuxt"` 就位,写在其后的 `@theme` 覆盖 `--font-sans` 即可。完全由项目 CSS 控制字体时,不配置 `movk.theme.font` 即可: ```css [app/assets/css/main.css] @import "tailwindcss"; @import "@movk/nuxt"; @theme { --font-sans: "OPPO Sans", sans-serif; } ``` > [!NOTE] > > 中文字体经 > > unicode-range > > 分包,浏览器只下载页面实际用到字符所在的分片。因此这些字体 > > 不能 > > 交给 > > @nuxt/fonts > > 处理——它会在构建期把全部分片下载进产物,既失去按需加载,也丢掉跨项目共享的 CDN 缓存。 > > @movk/nuxt > > 已默认设置 > > ui.fonts: false > > ,项目无需重复声明。 ## 图标集 `ThemePicker` 与 `useTheme` 可在 Lucide、Phosphor、Tabler 三套图标集间实时切换,切换只改写 `appConfig.ui.icons`,不需要重新构建。 模块默认把自己组件用到的图标与这三套图标集一并注入 `@nuxt/icon` 的构建期图标包,运行时无需再向 Iconify API 请求。每套图标集需要各自的 `@iconify-json` 包才能内联: ```bash npx nypm add -D @iconify-json/lucide @iconify-json/ph @iconify-json/tabler ``` > [!NOTE] > > 未安装的图标集不会导致构建失败,只是相关图标退回运行时按需请求。默认图标集 > > lucide > > 缺失时模块会发出警告, > > ph > > 与 > > tabler > > 仅在切换图标集后才用到,缺失只记 debug 日志。 不需要这份注入时(例如项目自行管理图标包体积)可整体关闭,关闭后 movk 组件的图标改为运行时加载: ```ts [nuxt.config.ts] export default defineNuxtConfig({ movk: { icon: { clientBundle: false } } }) ``` ## 圆角 `--ui-radius` 保留三级优先级:`ThemePicker` 选择 > `movk.theme.radius` > 项目 CSS。缺省时模块不注入该变量,沿用 `@nuxt/ui` 的默认值(`0.25rem`),项目可在自己的 CSS 中覆盖: ```css [app/assets/css/main.css] @theme { --ui-radius: 0.5rem; } ``` ## 可选项定制 颜色别名、圆角档位、neutral 颜色均可在 `movk.theme` 中覆盖,作为 `ThemePicker` 与 `useTheme` 的取值范围: ```ts [nuxt.config.ts] export default defineNuxtConfig({ movk: { theme: { colors: ['primary', 'secondary', 'success', 'info', 'warning', 'error'], radiuses: [0, 0.125, 0.25, 0.375, 0.5], neutralColors: ['slate', 'gray', 'zinc', 'neutral', 'stone'] } } }) ``` > [!TIP] > See: /docs/getting-started/configuration > > 各字段含义见模块配置 · Theme ## 导出与复用 `ThemePicker` 与 `useTheme.exportCSS()` 导出的 CSS 变量可直接写入项目的 `main.css`,将运行时调试结果固化为默认主题: ```css [app/assets/css/main.css] @import "tailwindcss"; @import "@movk/nuxt"; :root { /* 粘贴 exportCSS() 导出的变量 */ } ``` ## ThemePicker 参考 ### 简介 `MThemePicker` 是一个可视化的主题配置组件,允许用户实时预览并自定义应用主题。统一调整 `primary`、`neutral`、圆角、图标集与颜色模式,并支持导出 CSS 变量与 `app.config.ts` 配置代码。 > [!NOTE] > See: https://github.com/nuxt/ui/tree/v4/docs/app/components/theme-picker > > 配置变更会存储在本地,下次访问时自动恢复。组件源码来自 Nuxt UI > [!NOTE] > > MThemePicker > > 属于主题模块的一部分。若将 > > movk.theme.enabled > > 设为 > > false > > ,该组件将不会被注册。 ### 用法 `MThemePicker` 通常作为全局主题配置入口,放置在应用头部或工具栏: > [!TIP] > > 当前主题 token 在面板操作后即时更新,便于确认配置是否生效。配合 > > useTheme > > 读取响应式状态: ```vue [ComponentsThemePickerStateExample.vue] ``` ### 功能特性 #### 主色调配置 - **Primary**:选择主品牌色,支持黑色或预设颜色 - **Neutral**:配置中性色调,影响文本和背景 #### 样式配置 - **Radius**:调整全局圆角大小(0–5 级别) - **Icons**:切换图标集(Lucide、Phosphor、Tabler) #### 颜色模式 支持三种颜色模式: - `light`:浅色模式 - `dark`:深色模式 - `system`:跟随系统 #### 导出配置 配置完成后可导出: - `main.css`:CSS 变量配置 - `app.config.ts`:应用配置代码 ### Theme ::component-theme :: ### Changelog See commit history for [src/runtime/components/theme-picker/主题系统.vue](https://github.com/mhaibaraai/movk-nuxt/commits/main/src/runtime/components/theme-picker/主题系统.vue). ## useTheme 参考 ### 简介 `useTheme` 暴露主题的响应式状态与导出方法,是 [`ThemePicker`](#themepicker-%E5%8F%82%E8%80%83) 组件的底层逻辑,可用于自定义主题面板或在业务逻辑中读写主题。 ### 返回值 ```ts const { // 颜色 color, primary, primaryColors, neutral, neutralColors, blackAsPrimary, setBlackAsPrimary, // 圆角 / 图标 / 模式 radius, radiuses, icon, icons, mode, modes, // 注入与状态 style, hasCSSChanges, hasConfigChanges, // 导出 exportCSS, exportConfig, resetTheme } = useTheme() ``` | 分组 | 成员 | 说明 | | --- | --- | --- | | 颜色 | `color` / `primary` / `primaryColors` | 主色及可选项 | | 颜色 | `neutral` / `neutralColors` | 中性色及可选项 | | 颜色 | `blackAsPrimary` / `setBlackAsPrimary` | 以黑色作为主色的开关 | | 圆角 | `radius` / `radiuses` | 当前圆角及可选档位 | | 图标 | `icon` / `icons` | 当前图标集及可选项 | | 模式 | `mode` / `modes` | 深色模式(`light`/`dark`/`system`)及可选项 | | 注入 | `style` | 需注入到页面的 CSS 变量 | | 状态 | `hasCSSChanges` / `hasConfigChanges` | 是否有相对默认的改动 | > [!TIP] > See: #themepicker-参考 > > 开箱即用的可视化主题面板见 ThemePicker 组件。 # 迁移到 v2 > 从 v1 升级到 v2 时需要处理的破坏性变更。 ## 概述 v2 重新聚焦 Schema 驱动的中后台能力(AutoForm、SearchForm、DataTable、API),移除了与 Nuxt UI 重叠或复用价值较低的组件。下文汇总升级时需要核对的行为变化与替代方案。 ## 升级步骤 1. **确认运行环境**。核对版本要求,再更新依赖和锁文件。见 [环境与 API](#%E7%8E%AF%E5%A2%83%E4%B8%8E-api)。 2. **替换已移除的用法**。检查 [组件与类型](#%E7%A7%BB%E9%99%A4%E7%9A%84%E7%BB%84%E4%BB%B6) 和 [AutoForm 控件](#%E7%A7%BB%E9%99%A4%E7%9A%84-autoform-%E6%8E%A7%E4%BB%B6%E7%B1%BB%E5%9E%8B)。 3. **核对行为变化**。检查 [表单、表格与语言](#%E8%A1%A8%E5%8D%95%E8%A1%A8%E6%A0%BC%E4%B8%8E%E8%AF%AD%E8%A8%80) 以及 [API 迁移表](https://nuxt.mhaibaraai.me/docs/api#%E4%BB%8E-v1-%E8%BF%81%E7%A7%BB%E5%88%B0-v2)。 4. **验证迁移结果**。运行项目的 lint、类型检查、测试和构建,回归项目使用到的流程。 ## 用 AI 迁移 在项目根目录打开 AI 编程助手,展开并复制提示词,或让助手读取 [本页的 Markdown 版本](https://nuxt.mhaibaraai.me/raw/docs/getting-started/migration.md)。提示词以 `v1.8.3` 为比较基准,也会检查项目是否需要补做更早的 v1 升级。 ```text 请把当前项目的 @movk/nuxt 从 v1 迁移到 v2,保留现有业务流程、数据格式和交互。 先读取项目说明、package.json、锁文件、Nuxt 或 Vite 配置、app.config、应用入口和 CI 配置。确认实际的 v1 版本、要安装的 v2 版本、包管理器,以及项目使用 Nuxt 还是 Vue + Vite。用目标版本的源码、类型声明和迁移指南核对下面的清单。若项目早于 v1.8.3,也检查实际版本到 v1.8.3 之间的差异。记录每项命中的文件和预期改动,再修改已用到的功能。 参考资料 - Movk Nuxt 迁移指南 https://nuxt.mhaibaraai.me/docs/getting-started/migration - 文档索引 https://nuxt.mhaibaraai.me/llms.txt - API 迁移表 https://nuxt.mhaibaraai.me/docs/api#从-v1-迁移到-v2 - Nuxt Auth Utils 迁移指南 https://nuxt.com/modules/auth-utils#migrate-from-v05 - Nuxt Site Config v5 变更 https://github.com/harlan-zw/nuxt-site-config/releases/tag/v5.0.0 迁移清单 1. 环境与依赖 - 将开发、CI 和部署环境的 Node.js 对齐到 ^22.22.3 || ^24.15.0 || >=26.0.0。Nuxt 模式要求 Nuxt ^4.6.4,并使用兼容的 Nuxt UI 4(至少 4.13.0)和 Zod 4(至少 4.3.6)。使用项目现有包管理器更新依赖和锁文件。 - Vue + Vite 项目检查 @movk/nuxt/vite、virtual:movk-plugins 与 CSS 入口。API 集成、上传下载和流式请求依赖 Nuxt。保留唯一的 Tailwind CSS 入口及 @import "@movk/nuxt"。 - 若项目单独锁定了 reka-ui,则与目标 Nuxt UI 对齐。若直接依赖 nuxt-site-config、tailwind-variants 或相关模块,检查跨主版本的配置与类型兼容。maska 和 colortranslator 已从模块移除,项目自己的调用仍需相应依赖。 2. 移除的组件、类型与主题 - 按项目实际组件前缀搜索模板、导入、组件类型和主题配置。迁移 WithClear、WithCopy、WithPasswordToggle、WithCharacterLimit、WithFloatingLabel、AsPhoneNumberInput 为 Nuxt UI 输入组件组合。 - PillGroup 按单选、多选、切换面板的实际用途换成 URadioGroup、UCheckboxGroup、UToggleGroup 或 UTabs。ColorChooser 可用 UColorPicker 和 UPopover 组合。Popconfirm 可用 UPopover 或 useMessageBox().confirm。SlideVerify 需要项目提供实现,保留原有验证流程。 - 检查自定义包装组件的 v-model、事件、插槽、可访问性和主题样式。移除旧组件的类型导入和对应主题条目。 3. AutoForm 与 SearchForm - 检查 schema 中的 withClear、withCopy、withPasswordToggle、withCharacterLimit、withFloatingLabel、asPhoneNumberInput、colorChooser、slideVerify、pillGroup。简单场景使用现有控件和 controlProps,需要保留增强交互时通过 defineControl 注册自定义控件并传入 controls。 - 将 AutoForm 的 :state 改为 v-model,表单绑定类型使用 z.input,并按 schema 的输出类型检查提交回调。reset() 恢复基线并补齐 schema 默认值,clear() 只保留默认值。两者原地更新状态,AutoForm 的事件带状态快照。编辑表单异步加载记录后,用 setBaseline() 设置重置目标。 - 检查条件显示对嵌套对象、布局字段、校验和提交值的影响。meta.if 隐藏的字段不参与校验,hiddenValue 控制是否清除模型里的值,字段级策略优先。核对依赖隐藏字段的校验和提交逻辑。 - SearchForm 的受控展开使用 v-model:expanded,初始展开可用 defaultExpanded。默认提交会修剪字符串、移除空字符串、null 和 undefined,保留 0 与 false。需要原值时用 :transform-payload="false",或传自定义函数。检查 reset/clear 事件中完整的 schema 字段及清空后的 undefined,尤其是用对象合并更新筛选条件的代码。SearchForm 仅渲染支持的叶子字段,跳过对象、数组字段和布局容器。 - 项目需要时再采用异步选项 asyncItems、数组项移动和复制、toggle / toggleGroup、isDirty / dirtyFields。启用 syncQuery 时,在 Nuxt 或 Vue Router 下检查首次恢复、前进与后退、query-restore 后刷新列表,以及替换或追加历史的行为。 4. DataTable 与 Tree - 将表格操作确认的 confirmText / cancelText / confirmButtonProps / cancelButtonProps 改为 confirmLabel / cancelLabel / confirmButton / cancelButton。把 paginationUi.text 改为完整模板,键为 empty、total、range、rangeUnknown、selected、pageSize,核对分页文档中的占位符。 - 回归客户端与服务端分页、树形展开、选中行和无限滚动。使用 key 数组的选中、展开、列显隐状态时,检查对应 v-model 的绑定与初始值。检查空表格加载时的骨架屏,skeletonRows: 0 可使用 UTable 默认加载样式,已定义的 loading 插槽优先。 - 按需采用 columnSettings、persistKey 和 CSV 导出。exportCsv 只处理传给表格的数据,服务端分页需要全量导出时使用 exportServerCsv 和 serverCsvExport,并传入页面的外部筛选条件。 - Tree 回归父子级联、禁用节点、搜索前后选中与展开状态、懒加载失败重试。按需使用 leaf 策略、searchMethod / searchDebounce、reload()、getNode()、loadError 和 searchError。 5. 语言、日期与主题 - AutoForm、SearchForm、DataTable、Tree、DatePicker 和 MessageBox 的默认文案跟随 UApp locale,缺省回退英文。要保留中文则设置 。自定义文案可用 extendMovkLocale,组件已有的文案 props 也可继续使用。 - movk.zod 的校验文案本地化按需开启。locale: 'auto' 在客户端跟随 UApp,服务端用 fallback。movk:zod:config 的 customError 仅作用于当前应用的 AutoForm 和 SearchForm。Vue + Vite 通过插件选项 zod.customError 配置。检查直接调用 Zod 的校验以及自定义错误映射。 - useDateFormatter 未传 locale 时跟随 UApp,组件外回退 en。确认 toDate 对带时间值保留时分秒,convertData 保留原生 Date 和类实例。DatePicker 使用 v-model:open 控制弹层,popoverProps.defaultOpen 仅用于初始化非受控状态。检查 open() / close()、负时区、月和年模式的显示,以及表单字段尺寸和禁用态。 - 检查自定义主题前缀、中性色板及 SSR 首屏颜色。自定义组件前缀的项目同时验证 useMessageBox 的命令式调用。 6. API、认证与文件传输(Nuxt) - 搜索 $api(含 .use、.raw 和 .stream)、useApiFetch 及其变体、上传下载、chat transport 和 movk:api:* 钩子。将 skipBusinessCheck / skipUnwrap 改为语义取反的 businessCheck / unwrap,未设置的选项继续继承端点和全局配置。把 $api 的这些选项和 toast 从 context 移到请求选项顶层。 - 业务码检查与 dataKey 解包独立。直接返回裸数组或裸对象的端点,在 endpoints..response 中同时设置 businessCheck: false 和 unwrap: false。按请求覆盖端点默认值。自定义 onRequest / onResponse 会在内置钩子之后执行,依赖原始响应的调用应显式设置 unwrap: false。 - 用 ApiError.data?.kind 判断 business、http、network、timeout、aborted,按需读取 data.code 和 data.response。更新原先使用 FetchError、isBusinessError、error.response 或把 error.data 当成响应体的代码。movk:api:error 改为 (context, error),在重试结束后最多上报一次,主动中止不触发错误上报。检查 401、Toast、重试和 SSR 认证。 - 上传 timeoutMs 改为 timeout。上传下载继承端点的 publicHeaders 和请求钩子,注入的认证头优先于普通 headers。仅关闭业务校验时仍会解包。检查下载缺少 Content-Length 时的进度、JSON 错误响应及中止行为。SSE 和 chat transport 按流读取,JSON 错误仍按端点策略处理。 - 若使用 nuxt-auth-utils 会话,从 v0.5 升到 v0.6 时,按上游指南迁移会话配置、服务端 helpers 和部署环境。生产环境需设置 NUXT_APP_SECRET,移除旧的 NUXT_SESSION_PASSWORD 和 runtimeConfig.session.password,并安排用户重新登录。报告部署所需的变量名,保留密钥值在部署环境中。 7. 文档和 AI 集成 - 更新项目引用的 Movk Nuxt 文档链接。旧 composables 页按能力合并,SearchForm 归入 AutoForm,上传下载和流式请求归入 API,MCP、llms.txt 和 Skills 归入 AI 集成页。 改完后运行项目已有的 lint、类型检查、测试和构建,回归本次命中的表单提交、分页、认证或文件传输等流程。汇报修改的文件、核对结果、还需人工处理的部署项,以及无法验证的项目。 ``` ## 移除的组件 | 组件 | 替代方案 | | --- | --- | | `MWithClear` | `UInput` 组合写法,见 [Nuxt UI Input 示例](https://ui.nuxt.com/docs/components/input#with-clear-button) | | `MWithCopy` | `UInput` 组合写法,见 [Nuxt UI Input 示例](https://ui.nuxt.com/docs/components/input#with-copy-button) | | `MWithPasswordToggle` | `UInput` 组合写法,见 [Nuxt UI Input 示例](https://ui.nuxt.com/docs/components/input#with-password-toggle) | | `MWithCharacterLimit` | `UInput` 组合写法,见 [Nuxt UI Input 示例](https://ui.nuxt.com/docs/components/input#with-character-limit) | | `MWithFloatingLabel` | `UInput` 组合写法,见 [Nuxt UI Input 示例](https://ui.nuxt.com/docs/components/input#with-floating-label) | | `MAsPhoneNumberInput` | `UInput` 组合写法,见 [Nuxt UI Input 示例](https://ui.nuxt.com/docs/components/input#as-a-phone-number-input) | | `MPillGroup` | 按用途选择 `URadioGroup` / `UCheckboxGroup` 的 `variant="card"`、`UToggleGroup` 或 `UTabs` | | `MColorChooser` | `UColorPicker` 放入 `UPopover` | | `MSlideVerify` | 无内置替代,可自行实现或接入第三方人机验证服务 | | `MPopconfirm` | `UPopover` 内放置确认按钮,或使用命令式的 [`useMessageBox`](https://nuxt.mhaibaraai.me/docs/components/message-box#usemessagebox) | 同时移除了 `maska` 与 `colortranslator` 依赖,以及上述组件对应的 Props / Emits / Slots 类型导出(如 `WithClearProps`、`PillGroupProps`、`ColorChooserProps`)。 ## 移除的 AutoForm 控件类型 以下 `type` 值不再内置,继续使用会渲染 `[AutoForm] No control mapped` 提示: - `withClear`、`withPasswordToggle`、`withCopy`、`withCharacterLimit`、`withFloatingLabel`、`asPhoneNumberInput` - `colorChooser`、`slideVerify`、`pillGroup` 简单场景可通过 `controlProps` 配置现有控件。需要保留增强输入框时,在项目内封装组件,通过 `defineControl` 注册并把 `controls` 传给表单。自定义控件可以沿用原来的 `type` 名称。 ```ts [使用内置控件] const schema = afz.object({ // 之前:afz.string({ type: 'withPasswordToggle' }) password: afz.string({ controlProps: { type: 'password' } }), // 之前:afz.enum([...], { type: 'pillGroup' }) category: afz.enum(['全部', '前端', '后端'], { type: 'radioGroup', controlProps: { orientation: 'horizontal' } }) }) ``` ```ts [注册自定义控件] import PasswordInput from '~/components/PasswordInput.vue' const { afz, controls } = useAutoForm({ withPasswordToggle: defineControl({ component: PasswordInput, controlProps: { class: 'w-full' } }) }) ``` 详见 [控件与自定义控件](https://nuxt.mhaibaraai.me/docs/auto-form/controls#%E8%87%AA%E5%AE%9A%E4%B9%89%E6%8E%A7%E4%BB%B6)。 ## 环境与 API | 依赖 | 版本要求 | | --- | --- | | Node.js | `^22.22.3 \|\| ^24.15.0 \|\| >=26.0.0` | | Nuxt(Nuxt 模式) | `^4.6.4` | | Nuxt UI | `4.13.0` 或更高的兼容 v4 版本 | | Zod | `4.3.6` 或更高的兼容 v4 版本 | > [!NOTE] > See: /docs/api#从-v1-迁移到-v2 > > Nuxt 模式下的请求选项、错误处理、钩子和传输超时变更,见 API 迁移表。 使用纯 Vue 项目时,核对 [Vue / Vite 安装与配置](https://nuxt.mhaibaraai.me/docs/getting-started/vue)。 ## 表单、表格与语言 - **AutoForm 绑定**。使用 `v-model` 绑定输入状态,类型用 `z.input`。旧的 `:state` 仍可用,开发时会提示弃用。 - **表单重置与清空**。`reset()` 恢复基线并应用 schema 默认值,`clear()` 仅保留 schema 默认值。两者原地更新绑定对象并发出状态快照。编辑已有记录时,在加载后用 `setBaseline()` 设置重置目标。 - **SearchForm**。使用 `v-model:expanded` 控制展开。提交默认去除字符串首尾空白和空值,可设 `:transform-payload="false"` 保留原始数据。 - **DataTable**。操作确认改用 `confirmLabel`、`cancelLabel`、`confirmButton`、`cancelButton`。分页文案改用完整句子模板,键为 `empty`、`total`、`range`、`rangeUnknown`、`selected`、`pageSize`。 - **语言**。组件文案与 `useDateFormatter` 跟随 UApp 语言,缺省回退英文。需要中文时设定 UApp 语言,或对格式化函数传入 locale。 - **DatePicker**。`v-model:open` 优先于旧的 `popoverProps.open`,`popoverProps.defaultOpen` 仅初始化非受控状态。调用 `open()` / `close()` 前,把已有受控开关迁移到 `v-model:open`。 ## 文档路径调整 文档按能力域重新组织,旧链接会自动重定向: - `/docs/composables/*` 拆入对应能力域:`useAutoForm` → 表单、`useTheme` → 主题、`useMessageBox` / `useDateFormatter` → 对应组件页、上传下载与流式请求 → API - AutoForm 的字段类型页合并为 [字段类型](https://nuxt.mhaibaraai.me/docs/auto-form/field-types),`SearchForm` 移入表单章节 - AI 集成三页合并为 [AI 集成](https://nuxt.mhaibaraai.me/docs/getting-started/ai) # AI 集成 > 通过 MCP、llms.txt 与 Skills 让 AI 助手理解 Movk Nuxt。 ## MCP Server ### 什么是 MCP? MCP (Model Context Protocol) 是一个标准化协议,使 AI 助手能够访问外部数据源和工具。Movk Nuxt 提供 MCP 服务器,让 AI 工具能够直接访问组件信息、API 文档和使用示例。 ### 可用资源 MCP 服务器提供以下资源供 AI 发现和浏览: | 资源 URI | 描述 | | --- | --- | | `resource://docs/components` | 组件完整列表,包含元数据和分类信息 | | `resource://docs/composables` | 组合式函数完整列表,包含元数据和分类信息 | | `resource://movk-nuxt/auto-form` | AutoForm 系统完整文档,包含配置、API、字段定义和自定义选项 | | `resource://movk-nuxt/data-table` | DataTable 系统完整文档,包含列配置、树形、分页和样式定制 | | `resource://movk-nuxt/api` | API 系统完整文档,包含插件配置、Hooks、Composables 和进度上传/下载 | | `resource://docs/documentation-pages` | 所有可用文档页面的完整列表 | | `resource://docs/examples` | 所有可用示例代码和演示的完整列表 | 在 Claude Code 等工具中使用 `@` 访问这些资源。 ### 可用工具 #### 列表查询 | 工具名称 | 描述 | | --- | --- | | `list-components` | 列出所有 Movk Nuxt 组件及其分类和基本信息 | | `list-examples` | 列出文档站所有可用示例 | | `list-api` | 列出 API 系统文档,覆盖插件、Hooks 和 Composables | | `list-data-table` | 列出 DataTable 系统全部文档 | #### 详情获取 | 工具名称 | 描述 | | --- | --- | | `get-documentation-page` | 获取特定文档页面的完整内容。支持 `headings` 参数(h2 标题数组,如 `["Usage", "API"]`)以减少响应大小 | | `get-example` | 获取示例的实现代码,需提供 `exampleName` 参数(PascalCase) | | `get-component` | 获取指定组件的完整 API 文档与用法说明 | | `get-component-metadata` | 获取指定组件的元数据(props、slots、emits 等结构化信息) | #### 搜索过滤 | 工具名称 | 描述 | | --- | --- | | `search-documentation` | 按标题、路径、描述或文档章节搜索 | | `search-composables` | 按关键词搜索 Composables | | `search-icons` | 搜索可用图标 | | `search-components-by-category` | 按分类或关键词搜索组件 | | `search-auto-form-by-category` | 按关键词搜索 AutoForm 文档 | | `search-data-table-by-category` | 按分类或关键词搜索 DataTable 文档 | | `search-api-by-category` | 按分类或关键词搜索 API 系统文档 | > [!TIP] > > 对于大型文档页面,AI 可以使用 > > get-documentation-page > > 的 > > headings > > 参数仅获取相关部分(如「Usage」或「API」),减少响应大小并提高性能。 ### 可用提示 MCP 服务器为常见工作流提供引导式提示: | 提示名称 | 描述 | | --- | --- | | `find-component-for-usecase` | 根据使用场景推荐最适合的组件 | | `find-autoform-solution` | 根据表单需求推荐字段类型和配置方案 | | `implement-component-with-props` | 按指定 props 给出组件落地实现指引 | 在 Claude Code 等工具中使用 `/` 访问这些提示。 ### 配置 Movk Nuxt MCP 服务器使用 HTTP 传输,可在不同 AI 助手中配置。 #### ChatGPT > [!NOTE] > > 自定义连接器使用 MCP 功能需要 ChatGPT Pro 或 Plus 账户,仅在 Web 端可用。 将 Movk Nuxt 配置为 ChatGPT 连接器: 1. 启用开发者模式:进入「Settings」>「Connectors」>「Advanced settings」>「Developer mode」 2. 打开 ChatGPT 设置 3. 在 Connectors 标签页中创建新连接器: - 名称:`Movk Nuxt` - MCP server URL:`https://nuxt.mhaibaraai.me/mcp` - Authentication:`None` 4. 点击 Create 后续对话可在编辑器「Developer mode」工具列表中调用该连接器。 #### Claude Code > [!NOTE] > > 确保已安装 Claude Code。参阅 > > Anthropic 文档 > > 获取安装说明。 通过 CLI 命令添加服务器: ```bash claude mcp add --transport http movk-nuxt https://nuxt.mhaibaraai.me/mcp ``` #### Claude Desktop 1. 打开 Claude Desktop,进入「Settings」>「Developer」 2. 点击「Edit Config」打开本地 Claude 配置目录 3. 编辑 `claude_desktop_config.json`: ```json [claude_desktop_config.json] { "mcpServers": { "movk-nuxt": { "command": "npx", "args": [ "mcp-remote", "https://nuxt.mhaibaraai.me/mcp" ] } } } ``` 4. 重启 Claude Desktop,Movk Nuxt MCP 服务器即注册成功 #### Cursor ##### 一键安装 点击下方按钮,直接在 Cursor 中安装 Movk Nuxt MCP 服务器: ::install-button{url="https://nuxt.mhaibaraai.me/mcp"} :: ##### 手动配置 1. 打开 Cursor,进入「Settings」>「Tools & MCP」 2. 添加 Movk Nuxt MCP 服务器配置 或在项目根目录创建/编辑 `.cursor/mcp.json`: ```json [.cursor/mcp.json] { "mcpServers": { "movk-nuxt": { "type": "http", "url": "https://nuxt.mhaibaraai.me/mcp" } } } ``` #### Google Antigravity 1. 在编辑器顶部的 Agent 面板「...」下拉菜单中打开 MCP store 2. 点击「Manage MCP Servers」 3. 点击「View raw config」 4. 编辑 `mcp_config.json`: ```json [mcp_config.json] { "mcpServers": { "movk-nuxt": { "serverUrl": "https://nuxt.mhaibaraai.me/mcp" } } } ``` 5. 返回「Manage MCP Servers」并点击「Refresh」,Movk Nuxt MCP 服务器即出现在列表中 #### Gemini CLI 1. 定位 Gemini CLI 配置文件(通常位于 `~/.gemini/settings.json` 或环境变量指定路径) 2. 在 `mcpServers` 对象中追加配置: ```json [~/.gemini/settings.json] { "mcpServers": { "movk-nuxt": { "url": "https://nuxt.mhaibaraai.me/mcp" } } } ``` 3. 重启终端或重新加载 CLI,Movk Nuxt MCP 工具即可使用 #### Le Chat Mistral 1. 进入「Intelligence」>「Connectors」 2. 点击「Add Connector」按钮,选择「Custom MCP Connector」 3. 创建自定义 MCP 连接器: - Connector Name:`MovkNuxt` - Connector Server:`https://nuxt.mhaibaraai.me/mcp` #### Visual Studio Code ::install-button{url="https://nuxt.mhaibaraai.me/mcp" ide="vscode"} :: > [!NOTE] > > 需要安装 > > GitHub Copilot > > 和 > > GitHub Copilot Chat > > 扩展。 1. 打开 VS Code 命令面板(Ctrl/Cmd + Shift + P) 2. 输入「Preferences: Open Workspace Settings (JSON)」并执行 3. 在项目 `.vscode` 目录下创建或编辑 `mcp.json`: ```json [.vscode/mcp.json] { "servers": { "movk-nuxt": { "type": "http", "url": "https://nuxt.mhaibaraai.me/mcp" } } } ``` #### Windsurf 1. 进入「Settings」>「Windsurf Settings」>「Cascade」 2. 点击「Manage MCPs」>「View raw config」 3. 添加以下配置: ```json [.codeium/windsurf/mcp_config.json] { "mcpServers": { "movk-nuxt": { "type": "http", "url": "https://nuxt.mhaibaraai.me/mcp" } } } ``` #### Zed 1. 进入「Settings」>「Open Settings」 2. 打开 JSON 设置文件 3. 添加 context server 配置: ```json [.config/zed/settings.json] { "context_servers": { "movk-nuxt": { "source": "custom", "command": "npx", "args": ["mcp-remote", "https://nuxt.mhaibaraai.me/mcp"], "env": {} } } } ``` #### Opencode 1. 在项目根目录创建 `opencode.json` 2. 添加以下配置: ```json [opencode.json] { "$schema": "https://opencode.ai/config.json", "mcp": { "movk-nuxt": { "type": "remote", "url": "https://nuxt.mhaibaraai.me/mcp", "enabled": true } } } ``` #### GitHub Copilot Agent > [!NOTE] > > 需要仓库管理员权限以配置 GitHub Copilot coding agent 的 MCP 服务器。 若已在 VS Code 中完成配置,可基于相同结构调整(将 `servers` 键替换为 `mcpServers`),并显式声明 `tools` 列出可用工具。 1. 打开 GitHub 仓库 2. 进入「Settings」>「Code & automation」>「Copilot」>「Coding agent」 3. 在「MCP configuration」中添加: ```json { "mcpServers": { "movk-nuxt": { "type": "http", "url": "https://nuxt.mhaibaraai.me/mcp", "tools": ["*"] } } } ``` 4. 点击 Save 更多信息参阅 [Extend coding agent with MCP](https://docs.github.com/en/copilot/how-tos/use-copilot-agents/coding-agent/extend-coding-agent-with-mcp)。 ### 使用示例 配置完成后,可按 Movk Nuxt 四大能力域向 AI 助手提问: **AutoForm(Schema 驱动表单)** - 「如何用 Zod schema 自动生成表单?」 - 「支持哪些字段类型?如何注册自定义控件?」 - 「如何实现字段条件渲染与跨字段联动?」 - 「我想做一个用户注册表单,应该怎么组织 schema?」 **DataTable(数据表格)** - 「DataTable 的列定义有哪些字段,如何用函数式 column?」 - 「如何实现树形数据、列固定与列拖拽?」 - 「如何配置分页、加载更多与空状态?」 - 「我要做一个带行右键菜单的可编辑表格,应该用哪些 API?」 **API 系统(fetch 与进度)** - 「`useApiFetch` 和 `$fetch` 有什么区别?」 - 「如何配置多端点与自动认证?」 - 「如何监控文件上传/下载进度?」 - 「业务状态码与 Toast 提示如何接入?」 **独立组件与 Composables** - 「有哪些独立 UI 组件可用?」 - 「DatePicker、Tree、MessageBox 接受哪些 props?」 - 「`useDateFormatter`、`useTheme`、`useMessageBox` 怎么用?」 - 「我需要一个可选日期范围的选择器,推荐用哪个组件?」 AI 助手可以通过 MCP 工具查询文档和示例。也可以在支持 MCP 提示的客户端中手动选择引导式提示。 ## LLMs.txt ### 什么是 LLMs.txt? LLMs.txt 是专为大型语言模型(LLM)设计的结构化文档格式。Movk Nuxt 提供 LLMs.txt 文件,其中包含 Nuxt 模块的完整信息,使 AI 工具能够更好地理解和协助 Movk Nuxt 的开发。 这些文件针对 AI 消费进行了优化,包含组件 API、Composables 签名、Schema 定义、使用模式和最佳实践的结构化信息。 ### 可用端点 我们提供 LLMs.txt 端点来帮助 AI 工具访问我们的文档: - `/llms.txt` - 包含所有组件和 Composables 的结构化概览及其文档链接(约 5K tokens) - `/llms-full.txt` - 提供完整文档,包括实现细节、示例、类型定义和最佳实践(100K+ tokens) ### 选择正确的文件 > [!NOTE] > > 大多数用户应该从 /llms.txt 开始 > > - 它包含所有基本信息,适用于标准 LLM 上下文窗口。仅当您需要完整的实现示例且 AI 工具支持大型上下文(200K+ tokens)时,才使用 > > /llms-full.txt > > 。 ### 重要使用说明 > [!WARNING] > > @ 符号必须手动输入 > > - 使用 Cursor 或 Windsurf 等工具时,必须在聊天界面中手动输入 > > @ > > 符号。复制粘贴会破坏工具识别它作为上下文引用的能力。 ### AI 工具使用方法 任何支持 LLMs.txt 的 AI 工具都可以使用这些端点来更好地理解 Movk Nuxt。 - "使用 Movk Nuxt 文档 [https://nuxt.mhaibaraai.me/llms.txt](https://nuxt.mhaibaraai.me/llms.txt)" - "遵循 Movk Nuxt 完整指南 [https://nuxt.mhaibaraai.me/llms-full.txt](https://nuxt.mhaibaraai.me/llms-full.txt)" ## Agent Skills `movk-nuxt` 是一个遵循 [Agent Skills 规范](https://agentskills.io/specification) 的使用指南。入口 `SKILL.md` 说明如何选择 Nuxt 或 Vue + Vite 模式,Agent 会按任务读取相关参考文件: | 任务 | 参考文件涵盖的内容 | | --- | --- | | 构建编辑表单或筛选栏 | Zod v4、AutoForm、自定义控件、SearchForm 和 URL 查询同步 | | 构建数据表格 | 列和行操作、树形数据、分页、滚动加载及 CSV 导出 | | 接入 Nuxt 项目的后端 | API 端点和认证、`useApiFetch`、传输进度、SSE 和 AI SDK 聊天传输 | | 选择界面组件 | DatePicker、Tree、MessageBox 和 ThemePicker | | 使用组合式函数 | 日期格式化、确认弹窗、主题设置和本地化 | ### 安装 在要使用此 skill 的项目目录中运行 [Skills CLI](https://skills.sh): ```bash npx skills add https://nuxt.mhaibaraai.me --skill movk-nuxt ``` 也可以直接从 GitHub 安装: ```bash npx skills add https://github.com/mhaibaraai/movk-nuxt/tree/main/docs/skills/movk-nuxt --skill movk-nuxt ``` 默认安装到当前项目。可以追加 `--agent codex` 或 `--agent claude-code` 来指定客户端,也可以追加 `--global` 以便跨项目使用。 #### Cursor 一键安装 [安装 Skill](cursor://anysphere.cursor-deeplink/install-skill?url=https://github.com/mhaibaraai/movk-nuxt/tree/main/docs/skills/movk-nuxt) ### 使用 在 Agent 对话中提及 `movk-nuxt` 并说明任务,例如「用 Movk Nuxt 做一个能把筛选条件同步到 URL 的搜索表单」。手动调用方式因客户端而异,例如 Claude Code 中可输入 `/movk-nuxt`。 可以同时配置 [MCP Server](#mcp-server),让 Agent 在使用 skill 的同时按需查询组件属性、事件和示例。文档站提供 [Skill 索引](https://nuxt.mhaibaraai.me/.well-known/skills/index.json),也可以在 GitHub 浏览 [完整 skill 目录](https://github.com/mhaibaraai/movk-nuxt/tree/main/docs/skills/movk-nuxt)。 # 快速开始 > 了解 AutoForm 的核心设计理念和基本使用方式。 ## 什么是 AutoForm AutoForm 是一个基于 Zod Schema 的自动表单生成系统。通过声明式的 Schema 定义,自动生成完整的表单界面,包括输入控件、验证规则和布局结构。 > [!NOTE] > > **核心优势** > > - **Schema 即表单** - 一份 Schema 同时定义数据结构、验证规则和 UI 配置 > - **类型安全** - 完整的 TypeScript 类型推断,从 Schema 到表单数据 > - **零模板代码** - 无需手写 `v-for` 或重复的表单字段模板 ## 基础示例 创建一个简单的用户注册表单: ```vue [AutoFormBasicExample.vue] ``` ## API ### Props ```ts /** * Props for the MAutoForm component */ interface MAutoFormProps { /** * Zod 对象 schema,定义表单字段 */ schema: S; /** * 表单状态对象,原地修改。 */ state?: N extends false ? FormState : never | undefined; /** * 外部 loading 状态,与 `loadingAuto` 的提交中状态合并 */ loading?: boolean | undefined; /** * 是否显示默认提交按钮 * @default true */ submit?: boolean | undefined; /** * 提交按钮属性 */ submitButtonProps?: ButtonProps | undefined; /** * 数组字段添加按钮属性 */ addButtonProps?: ButtonProps | undefined; /** * 自定义控件映射 */ controls?: AutoFormControls | undefined; /** * 全局字段元数据配置 */ globalMeta?: ZodAutoFormFieldMeta | undefined; /** * 是否启用自动 loading 功能。 * @default true */ loadingAuto?: boolean | undefined; /** * 表单验证时机,详见 UForm 的 validateOn 属性 * @default [] */ validateOn?: FormInputEvents[] | undefined; /** * 字段被 `meta.if` 隐藏时如何处理其值:`keep` 保留,`clear` 置为 `undefined`;字段 meta 的 `hiddenValue` 优先。 * 无论哪种策略,隐藏字段都不参与校验,也不出现在提交数据中 * @default 'keep' */ hiddenValue?: "clear" | "keep" | undefined; /** * 提交回调;返回 Promise 时配合 `loadingAuto` 显示加载状态 */ onSubmit?: (): void | (event: FormSubmitEvent>): void | undefined; ui?: Record & { root?: SlotClass; base?: SlotClass; collapsible?: SlotClass; header?: SlotClass; footer?: SlotClass; actions?: SlotClass; } | undefined; id?: string | number | undefined; /** * Custom validation function to validate the form state. */ validate?: (state: Partial>): FormError[] | Promise[]> | undefined; /** * Disable all inputs inside the form. */ disabled?: boolean | undefined; /** * The `name` attribute of the form element. * For nested forms (`nested` is true), this is also used as the path of the form's state within its parent form. */ name?: string | undefined; /** * Delay in milliseconds before validating the form on input events. * @default `300` */ validateOnInputDelay?: number | undefined; /** * If true, applies schema transformations on submit. * @default `true` */ transform?: T | undefined; /** * If true, this form will attach to its parent Form and validate at the same time. * @default `false` */ nested?: N | undefined; acceptcharset?: string | undefined; action?: string | undefined; autocomplete?: string | undefined; enctype?: string | undefined; method?: string | undefined; novalidate?: false | true | "true" | "false" | undefined; target?: string | undefined; modelValue?: AutoFormStateType | undefined; } ``` ### Slots ```ts /** * Slots for the MAutoForm component */ interface MAutoFormSlots { header(): any; footer(): any; submit(): any; field-label(): any; field-hint(): any; field-description(): any; field-help(): any; field-error(): any; field-default(): any; } ``` > [!NOTE] > > 除了组件级别的插槽外,AutoForm 还支持字段级别的动态插槽,并提供完整的 TypeScript 类型推断和编辑器自动补全。 > > | 插槽模式 | 示例 | 说明 | > | --- | --- | --- | > | `field-{slotType}` | `field-label`, `field-default` | 通用插槽,适用于所有字段 | > | `field-{slotType}:{fieldKey}` | `field-label:username`, `field-default:email` | 特定字段插槽,享受**完整类型推导** | > | `field-{position}:{fieldKey}` | `field-before:profile`, `field-content:tasks` | 嵌套字段布局插槽 | ### Emits ```ts /** * Emitted events for the MAutoForm component */ interface MAutoFormEmits { error: (payload: [FormErrorEvent]) => void; reset: (payload: [state: Partial>]) => void; clear: (payload: [state: Partial>]) => void; update:modelValue: (payload: [value: AutoFormStateType | undefined]) => void; } ``` ### Expose 您可以通过 [`useTemplateRef`](https://vuejs.org/api/composition-api-helpers.html#usetemplateref) 访问该类型化组件实例。 | Name | Type | | --- | --- | | `reset()` | `void`
恢复表单基线并应用 schema 默认值 | | `clear()` | `void`
清空表单并保留 schema 默认值 | | `formRef` | `Ref \| null>`
UForm 组件的模板引用,可访问底层表单的所有方法和属性 | > [!TIP] > See: https://ui.nuxt.com/docs/components/form#expose > > 通过 > > formRef > > 可以访问 UForm 的所有底层功能,包括 > > submit() > > 、 > > validate() > > 、 > > clear() > > 、 > > getErrors() > > 、 > > setErrors() > > 等方法,以及 > > errors > > 、 > > disabled > > 、 > > dirty > > 、 > > dirtyFields > > 、 > > touchedFields > > 、 > > blurredFields > > 等响应式属性。详见 Nuxt UI Form 文档。 ## Theme ::component-theme{slug="AutoForm"} :: ## Changelog See commit history for [src/runtime/components/快速开始.vue](https://github.com/mhaibaraai/movk-nuxt/commits/main/src/runtime/components/快速开始.vue). # 实战示例 > 登录、注册分组校验、多文件上传与横向搜索表单等 AutoForm 组合场景。 ## 登录表单 组合邮箱、密码与记住我字段,`loadingAuto` 接管异步提交态: ```vue [AutoFormRecipeLoginExample.vue] ``` ## 注册分组校验 嵌套 `object` 分组字段,`refine` 校验确认密码一致: ```vue [AutoFormRecipeRegisterExample.vue] ``` ## 多文件上传 `afz.array(afz.file())` 渲染多文件字段,提交后汇总附件数量: ```vue [AutoFormRecipeUploadExample.vue] ``` ## 横向搜索表单 `globalMeta` 横向排布筛选项,`footer` 插槽承载操作按钮,`submit-button` 关闭内置按钮: ```vue [AutoFormRecipeSearchExample.vue] ``` # 字段类型 > afz 各字段类型到控件的映射与配置。 ## String 字符串 > [!NOTE] > See: https://zod.dev/api#strings > > 使用 > > afz.string() > > 创建字符串字段: ### `Input` > [!NOTE] > See: https://ui.nuxt.com/docs/components/input > > Input 组件文档 基础输入框,通过 `controlProps` 配置图标、颜色等属性: ```vue [AutoFormFieldStringInputExample.vue] ``` ### `Textarea` > [!NOTE] > See: https://ui.nuxt.com/docs/components/textarea > > Textarea 组件文档 多行文本输入,设置 `type: 'textarea'`,支持自动调整高度: ```vue [AutoFormFieldStringTextareaExample.vue] ``` ### `PinInput` > [!NOTE] > See: https://ui.nuxt.com/docs/components/pin-input > > PinInput 组件文档 验证码或 PIN 码输入,设置 `type: 'pinInput'`: ```vue [AutoFormFieldStringPinInputExample.vue] ``` ### `InputMenu` > [!NOTE] > See: https://ui.nuxt.com/docs/components/input-menu > > InputMenu 组件文档 支持输入和下拉选择,设置 `type: 'inputMenu'`: ```vue [AutoFormFieldStringInputMenuExample.vue] ``` ### 动态类型 通过交互式示例切换输入框与文本域,并调整尺寸、颜色、行数、最大长度等配置。 ```vue [AutoFormFieldStringTypeExample.vue] ``` ## Number 数字 > [!NOTE] > See: https://zod.dev/api#numbers > > 使用 > > afz.number() > > 创建数字字段: ### `InputNumber` > [!NOTE] > See: https://ui.nuxt.com/docs/components/input-number > > InputNumber 组件文档 基础数字输入框,支持整数、小数、范围限制等配置: ```vue [AutoFormFieldNumberInputExample.vue] ``` ### `Slider` > [!NOTE] > See: https://ui.nuxt.com/docs/components/slider > > Slider 组件文档 数值滑块,设置 `type: 'slider'`,适合有明确范围的数值选择: ```vue [AutoFormFieldNumberSliderExample.vue] ``` ### `InputRating` > [!NOTE] > See: https://ui.nuxt.com/docs/components/input-rating > > InputRating 组件文档 评分输入,通过 `component` 直接传入 `UInputRating` 组件实例,支持半星粒度与自定义星数: ```vue [AutoFormFieldNumberInputRatingExample.vue] ``` ## Boolean 布尔 > [!NOTE] > See: https://zod.dev/api#booleans > > 使用 > > afz.boolean() > > 创建布尔值字段: ### `Checkbox` > [!NOTE] > See: https://ui.nuxt.com/docs/components/checkbox > > Checkbox 组件文档 默认的复选框控件,适合单个选项的勾选: ```vue [AutoFormFieldBooleanCheckboxExample.vue] ``` ### `Switch` > [!NOTE] > See: https://ui.nuxt.com/docs/components/switch > > Switch 组件文档 开关控件,设置 `type: 'switch'`,适合功能的启用/禁用: ```vue [AutoFormFieldBooleanSwitchExample.vue] ``` ### `Toggle` 用 `afz.boolean({ type: 'toggle' })` 渲染可按下的布尔值按钮,适合置顶等操作。通过 `controlProps.label` 设置按钮文字。 ```vue [AutoFormFieldBooleanToggleExample.vue] ``` ## Date 日期时间 > [!TIP] > See: /docs/components/date-picker#usedateformatter > > useDateFormatter 文档:基于 @internationalized/date 的日期格式化和处理工具。 使用 `afz.calendarDate()` 创建日期字段,基于 [`@internationalized/date`](https://react-spectrum.adobe.com/internationalized/date/index.html) 提供强大的日期处理能力: ### 日期选择器 > [!NOTE] > See: https://ui.nuxt.com/docs/components/calendar > > Calendar 组件文档 单日期选择,支持日期格式化和验证: ```vue [AutoFormFieldDatePickerExample.vue] ``` ### 日期范围 日期范围选择,设置 `controlProps.range: true`: ```vue [AutoFormFieldDateRangeExample.vue] ``` ### 日期输入框 > [!NOTE] > See: https://ui.nuxt.com/docs/components/input-date > > InputDate 组件文档 使用 `afz.inputDate()` 创建日期输入框,基于 `UInputDate` 组件提供原生的日期输入体验。 #### 单日期输入 简洁的日期输入框,适合表单填写场景: ```vue [AutoFormFieldInputDateExample.vue] ``` #### 日期范围输入 支持范围选择的日期输入框: ```vue [AutoFormFieldInputDateRangeExample.vue] ``` ### 时间输入框 使用 `afz.inputTime()` 创建时间输入框,返回 `Time` 类型(来自 `@internationalized/date`): > [!NOTE] > See: https://ui.nuxt.com/docs/components/input-time > > InputTime 组件文档 ```vue [AutoFormFieldInputTimeExample.vue] ``` ### ISO 格式字符串 对于需要 ISO 标准格式字符串的场景,提供三种工厂方法: - `afz.isoDate()` - 验证 `YYYY-MM-DD` 格式 - `afz.isoTime()` - 验证 `HH:MM[:SS[.s+]]` 格式 - `afz.isoDatetime()` - 验证 ISO 8601 完整格式 ```vue [AutoFormFieldIsoExample.vue] ``` ## Enum 枚举 > [!NOTE] > See: https://zod.dev/api#enums > > 使用 > > afz.enum() > > 创建枚举字段: > [!TIP] > > 用于覆盖默认控件和配置元数据,支持三种配置方式: > > 不指定控件类型,使用默认的 `select` 控件: > > ```ts > afz.enum(['a', 'b'], { > label: '选择选项', > hint: '请选择一个' > }) > ``` > > 通过 `type` 覆盖默认控件,同时保持输出类型不变: > > ```ts > afz.enum(['a', 'b', 'c'], { > type: 'radioGroup', // 覆盖默认的 select > controlProps: { > items: [ > { label: '选项A', value: 'a' }, > { label: '选项B', value: 'b' } > ] > } > }) > // 输出类型仍为:'a' | 'b' | 'c' > // 但使用 radioGroup 渲染 > ``` > > 直接传入自定义组件实例: > > ```ts > import MyEnumControl from './MyEnumControl.vue' > > afz.enum(['a', 'b'], { > component: MyEnumControl, > controlProps: { /* ... */ } > }) > ``` > [!TIP] > > 枚举值配置:`controlProps.items` 以最高优先级决定渲染内容,`enum()` 的第一个参数决定输出类型,两者可以兼用。 > > - 方式 1:自动提取枚举值,系统会自动将枚举值转换为 `items`:```ts > const Fruits = ['apple', 'banana', 'orange'] as const > > const schema = afz.object({ > fruit: afz.enum(Fruits, { > type: 'selectMenu', > controlProps: { > placeholder: '选择水果' > // 系统自动转换:items: ['apple', 'banana', 'orange'] > } > }) > }) > ``` > - 方式 2:手动提供 items,使用空数组 `[]` 作为第一个参数,完全由 `items` 决定类型和渲染:```ts > const schema = afz.object({ > fruit: afz.enum([], { > type: 'selectMenu', > controlProps: { > valueKey: 'value', > items: [ > { label: '苹果', value: 'apple' }, > { label: '香蕉', value: 'banana' } > ] > } > }) > }) > ``` > - 方式 3:类型 + 自定义显示(推荐),同时使用枚举参数和 `items`,既保证类型安全,又自定义显示:```ts > const schema = afz.object({ > gender: afz.enum(['male', 'female', 'other'], { > type: 'radioGroup', > controlProps: { > items: [ > { label: '男', value: 'male' }, > { label: '女', value: 'female' }, > { label: '其他', value: 'other' } > ] > } > }) > }) > // 输出类型:'male' | 'female' | 'other' > // 显示内容:男 / 女 / 其他 > ``` ### `Select` > [!NOTE] > See: https://ui.nuxt.com/docs/components/select > > Select 组件文档 原生选择框,适合简单的枚举值: ```vue [AutoFormFieldEnumSelectExample.vue] ``` ### `SelectMenu` > [!NOTE] > See: https://ui.nuxt.com/docs/components/select-menu > > SelectMenu 组件文档 下拉菜单,设置 `type: 'selectMenu'`,支持搜索、图标、分组: ```vue [AutoFormFieldEnumSelectMenuExample.vue] ``` ### `RadioGroup` > [!NOTE] > See: https://ui.nuxt.com/docs/components/radio-group > > RadioGroup 组件文档 单选按钮组,设置 `type: 'radioGroup'`,适合 2-4 个选项: ```vue [AutoFormFieldEnumRadioGroupExample.vue] ``` ### `ToggleGroup` 用 `afz.enum(values, { type: 'toggleGroup' })` 渲染单选按钮组。AutoForm 根据枚举值生成选项,也可以通过 `controlProps.items` 提供自定义标签。再次点击已选项会清空选值。允许清空时,给 schema 加上 `.optional()`。 多选使用 `afz.array()`,设置 `type: 'toggleGroup'`,并在 `controlProps` 中传入 `type: 'multiple'` 和选项对象数组。表单值是所选选项的 `value` 数组。 ```vue [AutoFormFieldToggleGroupExample.vue] ``` ## File 文件 > [!NOTE] > > 使用 > > afz.file() > > 创建文件上传字段: ### 单文件上传 基础的单文件上传: ```vue [AutoFormFieldFileSingleExample.vue] ``` ### 多文件上传 多文件上传,使用 `array` 配合 `type: 'file'`: ```vue [AutoFormFieldFileMultipleExample.vue] ``` # 对象与数组 > 嵌套对象与动态数组字段的渲染与增删。 ## Object 对象 > [!NOTE] > > 两种调用方式的区别 > > ```ts > // 直接调用 > afz.object(shape, meta?) > > // 柯里化调用(类型参数 `` 仅用于 IDE 提示,不影响运行时验证。) > afz.object()(shape, meta?) > ``` > > ```ts > const schema = afz.object({ > name: afz.string(), > age: afz.number() > }) > ``` > > ```ts > interface UserInfo { > name: string > age: number > email: string > } > > const schema = afz.object()({ > name: afz.string(), // IDE 会提示 name | age | email > email: afz.email() > }) > ``` ### 通用对象 通用对象类型通常与 `selectMenu` 结合使用,用于选择复杂数据结构: ```vue [AutoFormFieldObjectBasicExample.vue] ``` ### 嵌套对象 嵌套对象结构,支持折叠展开: ```vue [AutoFormFieldObjectNestedExample.vue] ``` ### 类型化对象 > [!TIP] > > 使用 TypeScript 接口约束对象结构,在定义 schema 时获得字段名的 IDE 提示: ```vue [AutoFormFieldObjectTypedExample.vue] ``` > [!NOTE] > > 三种对象工厂对应不同的额外字段处理策略: > > ```ts > const schema = afz.object({ name: afz.string() }) > > schema.parse({ name: '张三', extra: 'removed' }) > // 结果:{ name: '张三' } > ``` > > ```ts > const schema = afz.looseObject({ name: afz.string() }) > > schema.parse({ name: '张三', extra: 'kept' }) > // 结果:{ name: '张三', extra: 'kept' } > ``` > > ```ts > const schema = afz.strictObject({ name: afz.string() }) > > schema.parse({ name: '张三', extra: 'error' }) > // 错误:Unrecognized key(s) in object: 'extra' > ``` ## Array 数组 > [!NOTE] > See: https://zod.dev/api#arrays > > 使用 > > afz.array() > > 创建数组字段: ### ElementSchema 定义数组元素的类型,决定输出类型为 `T[]`: ```ts // 字符串数组 const schema1 = afz.array(afz.string()) // 输出类型:string[] // 对象数组 const schema2 = afz.array(afz.object({ name: afz.string(), age: afz.number() })) // 输出类型:{ name: string, age: number }[] ``` ### Meta > [!NOTE] > > 用于 > > 覆盖数组元素的默认控件 > > 和配置元数据,同时保持输出类型不变: > [!TIP] > > 对于对象数组(如 `afz.array(afz.object({...}))`),系统会自动使用折叠面板渲染,无需手动指定控件类型。 > > 不指定控件类型,数组元素使用默认映射: > > ```ts > afz.array(afz.string(), { > label: '标签列表', > hint: '添加多个标签' > }) > // string[] - 元素默认使用 input 控件 > ``` > > 通过 `type` 覆盖数组**元素的默认控件**,输出类型保持不变: > > ```ts > afz.array(afz.string(), { > type: 'checkboxGroup', // 覆盖 string 的默认 input 控件 > controlProps: { > items: ['reading', 'gaming', 'sports'] > } > }) > // 输出类型仍为:string[] > // 但使用 checkboxGroup 渲染(多选) > ``` > > `afz.string()` 本来会被映射为 `input` 控件,通过第二个参数的 `type: 'checkboxGroup'` 覆盖了这个默认映射,将其改为多选框形式。 > > 直接传入自定义组件实例: > > ```ts > import MyArrayControl from './MyArrayControl.vue' > > afz.array(afz.string(), { > component: MyArrayControl, > controlProps: { /* ... */ } > }) > ``` ### 异步选项与数组操作 `asyncItems` 按 `deps` 重新加载选项,`load` 可将传入的 `signal` 交给请求。`sortable`、`duplicable` 开启数组项移动和复制,`min`、`max` 和 `length` 限制添加与删除。 ```vue [AutoFormAsyncItemsArrayExample.vue] ``` ### `InputTags` > [!NOTE] > See: https://ui.nuxt.com/docs/components/input-tags > > InputTags 组件文档 标签输入框,设置 `type: 'inputTags'`,适合自由文本标签: ```vue [AutoFormFieldArrayInputTagsExample.vue] ``` ### `CheckboxGroup` > [!NOTE] > See: https://ui.nuxt.com/docs/components/checkbox-group > > CheckboxGroup 组件文档 复选框组,设置 `type: 'checkboxGroup'`,适合预定义选项多选: ```vue [AutoFormFieldArrayCheckboxGroupExample.vue] ``` ### 对象数组 > [!NOTE] > See: https://ui.nuxt.com/docs/components/collapsible > > Collapsible 组件文档 对象数组自动使用折叠面板渲染,支持添加、删除项: ```vue [AutoFormFieldArrayObjectExample.vue] ``` # 控件 > 通过 type 字段将 schema 映射到 Nuxt UI 控件,或注册、直接传入自定义 Vue 组件扩展表单字段。 ## 概述 AutoForm 通过 `type` 字段将 schema 字段映射到具体的渲染控件,并支持两种方式扩展自定义控件: - **注册类型**:通过 `useAutoForm()` 注册控件类型,在 schema 中通过 `type` 引用,适合需要复用的控件 - **直接传入**:在 schema 中通过 `component` 直接传入组件实例,适合一次性使用 ## 内置控件 ### 默认映射 | afz 方法 | 默认控件 | 说明 | | --- | --- | --- | | `afz.string()` | `UInput` | 文本输入框 | | `afz.number()` | `UInputNumber` | 数字输入框 | | `afz.boolean()` | `UCheckbox` | 复选框 | | `afz.enum()` | `USelect` | 下拉选择器 | | `afz.file()` | `UFileUpload` | 文件上传 | | `afz.calendarDate()` | `DatePicker` | 日期选择器 | | `inputDate` | `UInputDate` | 日期输入框 | | `inputTime` | `UInputTime` | 时间输入框 | ### 可用的 type 值 通过 `type` 字段在 schema 中指定以下内置控件: | type 值 | 控件组件 | 说明 | | --- | --- | --- | | `textarea` | `UTextarea` | 多行文本输入框 | | `switch` | `USwitch` | 开关切换器 | | `toggle` | `UToggle` | 布尔值切换按钮 | | `slider` | `USlider` | 滑块选择器 | | `pinInput` | `UPinInput` | PIN 码输入框 | | `inputTags` | `UInputTags` | 标签输入框 | | `selectMenu` | `USelectMenu` | 下拉菜单选择器 | | `inputMenu` | `UInputMenu` | 输入菜单 | | `listbox` | `UListbox` | 列表选择器 | | `checkboxGroup` | `UCheckboxGroup` | 复选框组 | | `radioGroup` | `URadioGroup` | 单选框组 | | `toggleGroup` | `UToggleGroup` | 支持单选和多选的按钮组 | | `inputDate` | `UInputDate` | 日期输入框 | | `inputTime` | `UInputTime` | 时间输入框 | > [!NOTE] > See: /docs/getting-started/migration > > v2 移除了 > > withClear > > 、 > > withPasswordToggle > > 、 > > colorChooser > > 、 > > pillGroup > > 等控件类型,替代方案见迁移指南。 ### 控件总览 在 schema 中通过 `type` 引用内置控件,按文本、数字、布尔、选择、日期分组演示全部内置控件: ```vue [AutoFormControlsExample.vue] ``` ## 自定义控件 当内置控件无法满足需求时,可以通过注册或直接传入两种方式接入自定义 Vue 组件。 ### 注册控件 通过 `useAutoForm()` 注册控件,然后在 schema 中通过 `type` 字段引用: ```ts import { TagSelector } from '#components' const { afz, controls } = useAutoForm({ tagSelector: defineControl({ component: TagSelector, controlProps: { class: 'w-full' } // 全局 controlProps(可被字段级覆盖) }) }) ``` > [!TIP] > > 推荐优先使用 > > defineControl > > 注册自定义控件,以获得更稳定的 > > controlProps > > / > > controlSlots > > 类型提示。 > [!NOTE] > > 直接对象写法( > > tagSelector: { component: TagSelector } > > )仍然可用,且支持类型推导。 在 schema 中使用注册的控件类型: ```ts const schema = afz.object({ skills: afz .array(afz.string(), { type: 'tagSelector', // 指定控件类型 controlProps: { options: ['Vue.js', 'Nuxt', 'TypeScript'], max: 5 } }) .meta({ label: '技能标签' }) }) ``` 将 `controls` 传给 `MAutoForm`: ```vue ``` ### 直接传入组件 可以直接在 schema 的 meta 中传入组件实例,例如 `UInputRating`。 ```ts import { UInputRating } from '#components' const schema = afz.object({ rating: afz.number({ component: UInputRating, controlProps: { length: 10 } }).meta({ label: '评分' }) }) ``` > [!NOTE] > > 直接传入组件时, > > type > > 与 > > component > > 互斥,同时存在时以 > > component > > 为准。 ### 组件规范 自定义控件组件需满足以下要求。 #### 支持 v-model ```vue ``` #### 接受 controlProps `controlProps` 中的字段会作为 props 透传给控件组件。组件应声明对应的 props: ```vue ``` ## 示例 通过 `defineControl` 注册 `TagSelector` 为 `tagSelector` 控件类型,schema 中以 `type: 'tagSelector'` 引用,并通过 `controlProps` 传入候选标签与最大选中数: ```vue [AutoFormCustomControlExample.vue] ``` ```vue [app/components/TagSelector.vue] ``` # 元数据与布局 > 通过 meta 配置字段属性,并用 afz.layout 组织布局。 ## 元数据 ### `meta` 字段元数据 > [!NOTE] > See: https://ui.nuxt.com/docs/components/form-field#props > > 查看全部可用元数据属性、类型与配置优先级。 ```vue [AutoFormMetadataExample.vue] ``` ### `globalMeta` 全局元数据 ```vue [AutoFormAdvancedGlobalMetaExample.vue] ``` ## 布局 ### 示例 #### 简单容器布局 使用 `afz.layout` 创建一个基础的容器布局,通过 `class` 属性控制样式: ```vue [AutoFormLayoutSimpleExample.vue] ``` > [!NOTE] > > 布局字段的 key(如 > > $layout > > )以 > > $ > > 开头是惯例写法,但不是必需的。你可以使用任何字段名,只要其值为 > > afz.layout() > > 即可。 #### 网格布局 使用 CSS Grid 创建多列布局,通过字段级别的 `class` 控制跨列: ```vue [AutoFormLayoutGridExample.vue] ``` #### 响应式多列布局 利用 Tailwind 的响应式前缀,创建自适应不同屏幕尺寸的布局: ```vue [AutoFormLayoutResponsiveExample.vue] ``` > [!TIP] > > 使用 Tailwind 的响应式前缀( > > md: > > 、 > > lg: > > )可以轻松实现跨设备的自适应布局。字段可以通过 > > col-span-full > > 占据整行。 #### 嵌套布局 布局字段可以无限嵌套,构建复杂的层级结构: ```vue [AutoFormLayoutNestedExample.vue] ``` > [!WARNING] > > 嵌套布局的深度没有限制,但过深的嵌套可能影响可读性。建议保持在 2-3 层。 #### 手风琴布局 使用 Nuxt UI 的 `UAccordion` 组件,将字段组织在可折叠的面板中: ```vue [AutoFormLayoutAccordionExample.vue] ``` > [!TIP] > > fieldSlots > > 用于将不同字段分配到布局组件的不同插槽中。插槽名称需要与 > > items > > 中定义的 > > slot > > 对应。 #### 标签页布局 使用 `UTabs` 组件创建分页式表单,支持动态响应式配置: ```vue [AutoFormLayoutTabsExample.vue] ``` > [!TIP] > > 标签页布局展示了如何根据表单状态动态调整布局结构。切换用户类型时,标签页标题和字段分布会自动更新。 > [!WARNING] > > 在使用条件渲染( > > if > > )时,建议将字段标记为 > > .optional() > > ,避免验证错误。 ### API #### `AutoFormLayoutConfig` `afz.layout` 接受一个配置对象,包含以下属性: | 属性 | 类型 | 说明 | | --- | --- | --- | | `component` | `Component \| string` | 布局容器组件(默认:`'div'`) | | `class` | `string \| (context) => string` | CSS 类名,支持响应式函数 | | `props` | `object \| (context) => object` | 组件属性,支持响应式函数 | | `slots` | `Record VNode> \| (context) => ...` | 组件插槽内容 | | `fields` | `Record` | 包含的字段定义 | | `fieldSlot` | `string \| (context) => string` | 将**所有**字段渲染到指定插槽 | | `fieldSlots` | `Record \| (context) => ...` | 将**不同**字段分配到不同插槽 | #### `AutoFormNestedCollapsible` `collapsible` 属性接受一个配置对象,支持以下选项: | 属性 | 类型 | 默认值 | 说明 | | --- | --- | --- | --- | | `enabled` | `boolean` | `true` | 是否启用折叠功能 | | `defaultOpen` | `boolean` | | 默认是否展开 | | `open` | `boolean` | | 控制展开/收起状态(受控模式) | | `disabled` | `boolean` | | 禁用折叠功能(始终展开) | | `unmountOnHide` | `boolean` | `true` | 隐藏时卸载内容 | | `as` | `string` | `'div'` | 渲染的元素类型 | | `class` | `ClassNameValue` | | CSS 类名 | | `ui` | `{ root?: ClassNameValue; content?: ClassNameValue; }` | | UI 样式配置 | # 插槽 > 通过具名插槽自定义 AutoForm 的头尾、字段控件、字段前后与布局内容。 ## 概述 `AutoForm` 的插槽系统分为三个层级: - **表单插槽** - 自定义表单整体结构(`header`、`footer`、`submit`) - **字段插槽** - 微调每个字段的各个部分(`field-label`、`field-hint`、`field-error` 等) - **内容插槽** - 接管对象与数组字段的渲染或在字段前后插入内容(`field-content`、`field-before`、`field-after`) > [!TIP] > > 字段插槽支持 > > 通用模式 > > field-{type} > > 与 > > 命名模式 > > field-{type}:{path} > > ,让你既能统一样式,又能精确控制特定字段。命名模式优先级高于通用模式。 ## 示例 ### 表单级 `header`、`footer`、`submit` 接管表单的头部、尾部与提交区,均可读取 `loading`、`errors`、`state` 定制外层。 > [!WARNING] > > 使用 > > submit > > 插槽时需设置 > > :submit="false" > > 禁用默认提交按钮,否则会重复渲染。 ```vue [AutoFormSlotsFormExample.vue] ``` ### 通用字段 `field-label`、`field-description`、`field-hint`、`field-error` 统一覆盖所有字段的标签、描述、提示与错误区域。 ```vue [AutoFormSlotsGenericExample.vue] ``` ### 命名字段 `field-{type}:{path}` 仅替换指定字段的某个区域,未匹配的字段保持默认渲染。`field-default:{path}` 完全替换该字段的控件。 > [!NOTE] > > 命名插槽优先级高于通用插槽:同时存在 > > field-label > > 与 > > field-label:username > > 时, > > username > > 字段采用后者。 ```vue [AutoFormSlotsKeyedExample.vue] ``` ### 字段前后 `field-before:{path}`、`field-after:{path}` 在默认字段内容前后追加内容,不接管子字段的渲染与交互。 ```vue [AutoFormSlotsBeforeAfterExample.vue] ``` ### 对象内容 `field-content:{path}` 完全替换对象字段的渲染,通过 `setValue('key', value)` 以相对 key 更新子字段。 ```vue [AutoFormSlotsObjectContentExample.vue] ``` ### 数组内容 `field-content:{path}` 替换数组字段的渲染,`setValue` 既可写入整个列表,也可用 `[index].key` 路径更新单项。 ```vue [AutoFormSlotsArrayContentExample.vue] ``` ## API ### 表单级插槽 | Name | Description | | --- | --- | | `header` | 字段区域上方,适合标题、说明或状态提示 | | `footer` | 字段区域下方、提交按钮上方 | | `submit` | 接管提交区,需配合 `:submit="false"` | ### 字段插槽 | Slot | Parameter | Type | Description | | --- | --- | --- | --- | | `field-label` | `label` | `string` | 标签文本 | | `field-hint` | `hint` | `string` | 提示文本 | | `field-description` | `description` | `string` | 描述文本 | | `field-help` | `help` | `string` | 帮助文本 | | `field-error` | `error` | `string \| boolean` | 错误信息 | | `field-default` | `error` | `string \| boolean` | 接管基础类型字段控件的渲染(附带字段上下文) | > [!TIP] > > field-default > > 仅用于自定义基础类型字段(string、number、boolean 等)的控件。对象与数组字段请使用 > > field-content > > 。 ### 内容插槽 > [!WARNING] > > 内容插槽仅适用于 > > 对象字段与数组字段 > > ,对基础类型字段不生效。 | Name | Description | | --- | --- | | `field-content:{path}` | 完全接管对象/数组字段的渲染 | | `field-before:{path}` | 在默认内容前插入,不接管子字段 | | `field-after:{path}` | 在默认内容后插入,不接管子字段 | ### `setValue` 签名 `setValue` 支持以下重载形式: | Signature | Return | Description | | --- | --- | --- | | `setValue(value)` | `void` | 设置整个字段值 | | `setValue(relativePath, value)` | `void` | 按相对路径更新子字段:对象用 key(自动推断),数组用 `[index].key` | > [!NOTE] > > ```vue > // 直接设置当前字段的值 > setValue(newValue) > ``` > > ```vue > > ``` > > ```vue > > ``` ### `AutoFormFieldContext` 字段上下文类型,在插槽和响应式函数中可用: ```ts export interface AutoFormFieldContext { /** 表单数据 */ readonly state: S /** 字段路径 */ readonly path: P /** 字段值(可能为 undefined) */ readonly value: FieldValueType /** * 设置字段值的回调函数 * @description 支持多种调用方式: * 1. setValue(value) - 设置当前字段的整个值 * 2. setValue(key, value) - 设置子字段值(对象)或元素属性(数组) * 3. setValue(path, value) - 设置任意路径的值(字符串回退) * @example * // 对象字段 profile: { name, email, bio } * setValue({ name: '张三', email: 'test@example.com' }) // 设置整个对象 * setValue('name', '张三') // key 自动推断为 'name' | 'email' | 'bio' * * // 数组字段 tasks: [{ title, priority, completed }] * setValue([...tasks, newTask]) // 设置整个数组 * setValue('[0].title', '新标题') // 使用索引路径字符串 * * // 或者在遍历中直接使用属性名(推荐) * v-for="(task, index) in tasks" * setValue(`[${index}].title`, value) // 动态索引 */ setValue: { (value: FieldValueType): void >>( relativePath: K extends never ? string : K, value: any ): void (relativePath: string, value: any): void } /** 字段错误列表 */ readonly errors: unknown[] /** 表单提交加载状态 */ readonly loading: boolean /** 字段折叠状态 */ readonly open?: boolean /** 数组元素下标 */ readonly count?: number } ``` # 联动与提交 > 字段间响应式联动与表单提交处理。 ## 条件渲染 ### 概述 AutoForm 的 meta 字段均可传入**响应式函数** `(ctx) => value`,`ctx` 为 [`AutoFormFieldContext`](https://nuxt.mhaibaraai.me/docs/auto-form/slots#autoformfieldcontext)(含 `state`、`path`、`value`)。函数会随表单状态自动重算,从而实现条件渲染与字段联动。 > [!NOTE] > > 条件渲染有两种方式,行为不同: > > - **`if`** - 显示条件,结果为 `false` 时字段**不会创建**(不挂载、不参与校验)。 > - **`hidden`** - 是否隐藏,结果为 `true` 时字段**仍保留在 DOM 与表单数据中**,只是视觉隐藏。 ### 示例 #### 条件渲染 `if` 与 `hidden` 接收返回布尔值的函数:切换账户类型时,企业字段(`if`)按需挂载/卸载;勾选条款后,订阅字段(`hidden`)从隐藏切换为显示。 > [!TIP] > > 需要彻底排除字段(不校验、不提交)用 > > if > > ;只想临时隐藏但保留取值用 > > hidden > > 。 ```vue [AutoFormReactiveConditionalExample.vue] ``` #### 依赖联动 当控件属性取决于组件内的响应式状态时,可以省略回调参数。字面量会按控件属性类型推断,例如 `afz.string({ controlProps: () => ({ size: compact.value ? 'sm' : 'lg' }) })`。 函数式 `controlProps` 随其它字段变化重算控件属性。下例中城市选项依赖国家字段,并通过 `watch` 在国家变化时清空已失效的旧值。 > [!NOTE] > > 联动仅重算控件属性,不会自动清除旧值。需要清空失效选项时,配合 > > watch > > 手动重置。 ```vue [AutoFormReactiveDependentExample.vue] ``` > [!NOTE] > > 当 `items` 来源是**异步或外部响应式数据**(基于 `useApiFetch`、`useAsyncData` 的 `computed` / `ref`)时,务必用**函数式** `controlProps: () => ({ items: source.value })`,或直接传响应式来源 `items: source`,切勿写成 `items: source.value`。 > > schema 在 `setup` 期只构建一次,`source.value` 是当时的一次性快照:SSR 注水时数据恰好就绪会「看似正常」,但客户端导航重新挂载、异步数据尚未到达时会冻结为空数组,后续选项更新不再生效。函数式 `controlProps` 在渲染时实时求值,可规避此问题。 ### API #### `meta` | Name | Type | Description | | --- | --- | --- | | `if` | `ReactiveValue` | 显示条件,`false` 时字段不创建 | | `hidden` | `ReactiveValue` | 是否隐藏,`true` 时保留 DOM 但视觉隐藏 | > [!TIP] > > 除上述字段外, > > label > > 、 > > hint > > 、 > > description > > 、 > > controlProps > > 、 > > class > > 等 meta 字段同样支持 > > (ctx) => value > > 函数形态,按表单状态动态求值。 ## 提交 ### `loadingAuto` `@submit` 返回 Promise 时,提交按钮的 loading 由 AutoForm 自动管理(`loadingAuto` 默认开启): ```vue [AutoFormSubmitAutoExample.vue] ``` ### 手动 loading 控制 关闭 `loading-auto`,由 `submit-button-props.loading` 接管按钮状态: ```vue [AutoFormSubmitManualExample.vue] ``` ### 异常与校验事件 `@submit` 中处理异步异常;`@error` 接收字段校验失败: ```vue [AutoFormSubmitErrorExample.vue] ``` ### 编程式提交 通过 `useTemplateRef` 拿到表单实例后,可在外部触发 `formRef.submit()`、`reset()`、`clear()`(配合 `:submit="false"` 隐藏内置按钮): ```vue [AutoFormSubmitRefExample.vue] ``` # SearchForm > Schema 驱动的可折叠搜索表单组件。 ## 简介 `MSearchForm` 是一个 Schema 驱动的搜索表单组件,内置网格布局、搜索 / 重置按钮和折叠行为。当搜索项较多时,超出可见行数的字段会自动折叠,用户可点击展开 / 收起按钮查看全部搜索项。 > [!NOTE] > See: /docs/auto-form/quickstart > > 复用 AutoForm 基础设施(schema 内省、控件映射、字段渲染器),通过 Zod schema 定义搜索字段。 ## 用法 按 AutoForm schema 渲染字段,`cols` 控制栅格,内置搜索与重置按钮;点「搜索」触发校验并发出 `@submit`: ```vue [ComponentsSearchFormBasicExample.vue] ``` ### `v-model` 绑定 `v-model` 双向绑定表单数据,传入的初始值会被记录为重置基准:点「重置」恢复到该初始值而非清空。 ```vue [ComponentsSearchFormModelExample.vue] ``` ### `cols` 网格列数 `cols` 控制网格列数:传数字固定列数,传断点对象则列数随窗口宽度在 `sm`、`md`、`lg`、`xl` 间切换。 ```vue [ComponentsSearchFormColsExample.vue] ``` ```vue [ComponentsSearchFormResponsiveExample.vue] ``` ### `visibleRows` 折叠行为 `visibleRows` 控制可见行数,超出的字段折叠到展开区。下方拖动 `cols`、`visibleRows` 实时改变折叠阈值。 ```vue [ComponentsSearchFormExpandExample.vue] ``` ### `v-model:expanded` 受控展开 `v-model:expanded` 接管展开状态,优先级高于 `defaultExpanded`,可由外部按钮或逻辑驱动。 ```vue [ComponentsSearchFormExpandedControlledExample.vue] ``` ### `expandText` / `collapseText` / `icon` 展开按钮 `expandText`、`collapseText` 自定义展开 / 收起文案,`icon` 切换按钮图标,`collapseButtonProps` 透传按钮属性。 ```vue [ComponentsSearchFormToggleButtonExample.vue] ``` ### `actions` 操作按钮 `actions` 数组扩展或裁剪按钮: - 内置 `key: search` 自动绑定提交,`key: reset` 自动绑定重置 - 自定义 `key` 需提供 `onClick(ctx)`,`ctx` 含 `state`、`errors`、`search`、`reset`、`clear`、`toggle`、`loading`、`expanded` - 传 `actions: []` 关闭所有内置按钮,配合 `actions` slot 完全自定义 ```vue [ComponentsSearchFormHideButtonsExample.vue] ``` ```vue [ComponentsSearchFormCustomExample.vue] ``` ## 示例 ### 接管操作区 `#actions` 插槽暴露 `search`、`clear`、`loading`,可用自定义按钮替换默认操作区: ```vue [ComponentsSearchFormActionsSlotExample.vue] ``` ### 扩展布局区域 `header`、`footer`、`extraActions` 插入辅助内容,slot props 随展开与表单值更新: ```vue [ComponentsSearchFormLayoutSlotsExample.vue] ``` ### 异步提交与校验 `loading` 控制按钮加载态,`@error` 返回 Zod 校验失败的错误列表: ```vue [ComponentsSearchFormAsyncExample.vue] ``` ### URL 搜索历史 `syncQuery` 在 Nuxt 和 Vue Router 下恢复 schema 顶层查询字段。设 `replace: false` 可在提交、重置或清空时追加历史记录。`query-restore` 提供从 URL 恢复的字段,供列表刷新。Inertia 与无路由模式可继续使用普通表单。 ```vue [AutoFormSearchFormQueryExample.vue] ``` ## API ### Props ```ts /** * Props for the MSearchForm component */ interface MSearchFormProps { /** * Zod 对象 schema,定义表单字段 */ schema: S; /** * Nuxt 或 Vue Router 下同步 schema 顶层字段:挂载和路由变化时读取,提交、重置、清空时写入 * @default false */ syncQuery?: boolean | SearchFormQuerySync | undefined; /** * 提交前清洗载荷:`true` 时去除字符串首尾空白并剔除空值,传函数可自定义;`false` 时原样提交 * @default true */ transformPayload?: boolean | ((data: Partial>) => Partial>) | undefined; /** * 网格列数 * @default 3 */ cols?: number | { sm?: number | undefined; md?: number | undefined; lg?: number | undefined; xl?: number | undefined; } | undefined; /** * 可见行数(折叠时显示的行数) * @default 1 */ visibleRows?: number | undefined; /** * 动作按钮配置;不传时使用默认 [search, reset];传 [] 则关闭所有内置按钮 * @default [{ key: 'search', ... }, { key: 'reset', ... }] */ actions?: SearchFormAction[] | undefined; /** * 外部 loading 状态,与提交中状态合并,作用于 type==='submit' 或 key==='search' 的按钮 */ loading?: boolean | undefined; /** * 收起按钮属性 */ collapseButtonProps?: ButtonProps | undefined; /** * 展开/收起按钮图标 * @default 'i-lucide-chevron-down' */ icon?: any; /** * 展开按钮文本,缺省时取 locale 的 `searchForm.expand` */ expandText?: string | undefined; /** * 收起按钮文本,缺省时取 locale 的 `searchForm.collapse` */ collapseText?: string | undefined; /** * 默认展开状态 * @default false */ defaultExpanded?: boolean | undefined; /** * 自定义控件映射 */ controls?: AutoFormControls | undefined; /** * 全局字段元数据配置 */ globalMeta?: ZodAutoFormFieldMeta | undefined; /** * 是否启用自动 loading 功能。 * @default true */ loadingAuto?: boolean | undefined; /** * 表单验证时机,详见 UForm 的 validateOn 属性 * @default [] */ validateOn?: FormInputEvents[] | undefined; /** * 字段被 `meta.if` 隐藏时如何处理其值:`keep` 保留,`clear` 置为 `undefined`;字段 meta 的 `hiddenValue` 优先。 * 无论哪种策略,隐藏字段都不参与校验,也不出现在提交数据中 * @default 'keep' */ hiddenValue?: "clear" | "keep" | undefined; /** * 提交回调;返回 Promise 时配合 `loadingAuto` 显示加载状态 */ onSubmit?: (): void | (event: FormSubmitEvent>): void | undefined; ui?: Record & { root?: SlotClass; form?: SlotClass; visible?: SlotClass; grid?: SlotClass; header?: SlotClass; footer?: SlotClass; actions?: SlotClass; toggleWrapper?: SlotClass; toggle?: SlotClass; toggleIcon?: SlotClass; collapsed?: SlotClass; } | undefined; id?: string | number | undefined; /** * Custom validation function to validate the form state. */ validate?: (state: Partial>): FormError[] | Promise[]> | undefined; /** * Disable all inputs inside the form. */ disabled?: boolean | undefined; /** * The `name` attribute of the form element. * For nested forms (`nested` is true), this is also used as the path of the form's state within its parent form. */ name?: string | undefined; /** * Delay in milliseconds before validating the form on input events. * @default `300` */ validateOnInputDelay?: number | undefined; /** * If true, applies schema transformations on submit. * @default `true` */ transform?: true | undefined; /** * If true, this form will attach to its parent Form and validate at the same time. * @default `false` */ nested?: false | undefined; acceptcharset?: string | undefined; action?: string | undefined; autocomplete?: string | undefined; enctype?: string | undefined; method?: string | undefined; novalidate?: false | true | "true" | "false" | undefined; target?: string | undefined; /** * @default {} */ modelValue?: Partial> | undefined; expanded?: boolean | undefined; } ``` ### Emits ```ts /** * Emitted events for the MSearchForm component */ interface MSearchFormEmits { reset: (payload: [state: Partial>]) => void; clear: (payload: [state: Partial>]) => void; expand: (payload: [expanded: boolean]) => void; query-restore: (payload: [state: Partial>]) => void; error: (payload: [event: FormErrorEvent]) => void; update:modelValue: (payload: [value: Partial>]) => void; update:expanded: (payload: [value: boolean | undefined]) => void; } ``` > [!NOTE] > > @submit > > 转发自底层 > > UForm > > ,未列入上表。校验通过后触发,返回 > > FormSubmitEvent > > ,搜索条件位于 > > event.data > > ——这是接收查询参数的主要出口。 ### Slots ```ts /** * Slots for the MSearchForm component */ interface MSearchFormSlots { header(): any; footer(): any; actions(): any; extraActions(): any; field-label(): any; field-hint(): any; field-description(): any; field-help(): any; field-error(): any; field-default(): any; } ``` ### Expose 您可以通过 [`useTemplateRef`](https://vuejs.org/api/composition-api-helpers.html#usetemplateref) 访问该类型化组件实例。 | Name | Type | | --- | --- | | `formRef` | `Ref>`
UForm 组件引用 | | `submit()` | `void`
程序化触发表单提交(等价于点击 search 按钮) | | `reset()` | `void`
恢复到 baseline(首次挂载的 v-model 快照),并触发 `reset` 事件 | | `clear()` | `void`
清空表单所有字段为空值,并触发 `clear` 事件 | | `setBaseline(value?)` | `void`
设置 `reset()` 的恢复基准;不传参时使用当前 v-model 值 | | `expanded` | `ComputedRef`
当前展开 / 收起状态 | | `toggle()` | `void`
切换展开 / 收起,并 emit `expand` 与 `update:expanded` | ## Theme ::component-theme :: ## Changelog See commit history for [src/runtime/components/SearchForm.vue](https://github.com/mhaibaraai/movk-nuxt/commits/main/src/runtime/components/SearchForm.vue). # useAutoForm > 用于创建类型化 Zod Schema 和管理 AutoForm 控件的 composable。 ## 用法 使用自动导入的 `useAutoForm` composable 创建类型化的 Zod Schema,为 [`AutoForm`](https://nuxt.mhaibaraai.me/docs/auto-form/quickstart) 组件提供验证规则和控件配置。 ```vue ``` - `useAutoForm` 返回增强的 Zod 工厂对象 `afz`,支持为 Schema 附加 AutoForm 元数据。 - 元数据会自动在 Zod 的链式调用中持久化(如 `.optional()`, `.nullable()`, `.default()` 等)。 > [!NOTE] > > 使用 > > afz > > 工厂创建的 Schema 会自动拦截 Zod 的克隆方法,确保元数据在链式调用时不会丢失。 ## 自定义控件注册 当使用自定义控件时,需要通过 `defineControl` 辅助函数定义: ```ts const { afz, defineControl } = useAutoForm({ myInput: defineControl({ component: MyCustomInput, controlProps: { class: 'w-full' } }) }) // 现在可以在 Schema 中使用 const schema = afz.string({ type: 'myInput', controlProps: { variant: 'outline' } }) ``` ## API ### useAutoForm() `useAutoForm(controls?: AutoFormControls): UseAutoFormReturn`{lang="ts-type"} 创建 AutoForm 工厂和控件管理器。 #### Parameters **controls** (`AutoFormControls`): 自定义控件映射对象,用于扩展或覆盖默认控件,配合 defineControl 定义(见上方「自定义控件注册」)。 #### Returns **afz** (`TypedZodFactory`): 类型化的 Zod 工厂对象,用于创建带元数据的 Schema。 **defineControl** (`Function`): 定义控件的辅助函数。 **DEFAULT_CONTROLS** (`Object`): 默认控件映射对象。 **controls** (`Object`): 传入的自定义控件映射。 **getAutoFormMetadata** (`Function`): 从 Schema 中提取自定义元数据的工具函数。 ## Changelog See commit history for [src/runtime/composables/useAutoForm.ts](https://github.com/mhaibaraai/movk-nuxt/commits/main/src/runtime/composables/useAutoForm.ts). # 介绍 > 基于 TanStack Table 的声明式数据表格,含列配置、选择、展开、树形、分页、加载更多与完整 API 参考。 ## 简介 `MDataTable` 是基于 [`@tanstack/vue-table`](https://tanstack.com/table) 与 Nuxt UI `UTable` 封装的声明式数据表格。它把列定义、排序、列固定、列宽拖拽、选择、展开、树形、分页与加载更多统一收敛到一个 `columns` 数组与少量 props,并提供完整的 TypeScript 类型推断。 > [!NOTE] > > 核心理念: > > - **声明式列** —— 用对象数组描述列,数据列、选择列、索引列、展开列、操作列、分组列等通过 `accessorKey` 或 `type` 区分。 > - **全局 + 列级开关** —— `sortable`、`pinable`、`resizable`、`truncate`、`tooltip` 等既可全局启用,也可按列覆盖或传函数动态决定。 > - **类型安全** —— 列、单元格回调、事件处理均由 `DataTableColumn`、`DataTableProps` 等类型驱动。 ## 用法 一个 `columns` 数组即可声明选择列、索引列、固定列、单元格渲染与操作列,再配合 `row-key` 标识行、`sortable`/`pinable`/`resizable` 启用排序与列固定切换、列宽拖拽、`v-model:pagination` 分页,无需逐项拼装即得到完整能力: ```vue [DataTableBasicExample.vue] ``` ## 示例数据 本章所有示例的 `data` 均由以下工具函数派生,可直接复制到项目中复用: ```ts [app/composables/useTableMock.ts] export interface Person { id: string name: string email: string department: '研发' | '设计' | '产品' | '运营' | '市场' role: string level?: 'P5' | 'P6' | 'P7' | 'P8' status: 'active' | 'leave' | 'offboarded' salary: number joinedAt: string address: string bio: string children?: Person[] } const FIRST = ['张', '李', '王', '陈', '刘', '杨', '黄', '赵', '吴', '周', '徐', '孙'] const LAST = ['伟', '芳', '娜', '敏', '静', '丽', '强', '磊', '军', '洋', '勇', '涛', '明', '超'] const DEPARTMENTS: Person['department'][] = ['研发', '设计', '产品', '运营', '市场'] const ROLES = ['前端工程师', '后端工程师', '全栈工程师', 'UI 设计师', '产品经理', '数据分析师', '运营专员'] const LEVELS: Person['level'][] = ['P5', 'P6', 'P7', 'P8'] const STATUS: Person['status'][] = ['active', 'leave', 'offboarded'] const ADDRESSES = [ '上海市浦东新区张江高科技园区博云路 2 号 IBM 大厦 7 层 708', '北京市海淀区中关村大街 27 号中关村大厦 A 座 1502', '深圳市南山区科技园南区高新南九道 9 号深圳湾科技生态园 10 栋 B 座 2301', '广州市天河区珠江新城华夏路 16 号富力盈凯广场 38 楼', '杭州市余杭区文一西路 969 号阿里巴巴西溪园区 6 号楼 318', '成都市高新区天府大道中段 1199 号天府软件园 D 区 5 号楼 1207', '南京市建邺区江东中路 222 号高科荣域大厦 19 层', '武汉市洪山区光谷大道 70 号光谷国际企业中心 3 期 B 座 1808' ] const BIO_TEMPLATES = [ '在跨境电商团队负责供应链与履约链路建设,主导过日均百万单的实时调度系统重构,关注稳定性与成本平衡。', '长期投入大数据平台与离线计算调度,搭建过 PB 级数据仓库与数据治理体系,对数据质量与权限治理有较强经验。', '聚焦设计系统与组件库建设,推动跨产品视觉一致性,主导多次 Design Tokens 与暗色主题落地。', '负责自研低代码平台与 BFF 中间层,输出过若干内部脚手架与 CLI 工具,关注研发效率与可维护性。', '深耕实时音视频与 WebRTC 互动场景,主导过千万级直播间的延迟优化与弱网降级方案。', '在 To B SaaS 团队负责权限、计费与多租户体系,对 RBAC、ABAC 与审计合规有完整落地经验。', '负责风控与反作弊算法工程化,搭建过实时特征平台与规则引擎,覆盖支付、营销、社交多场景。', '聚焦移动端性能优化与跨端渲染框架,主导过启动耗时、内存与包体积的全链路治理。' ] function pick(list: readonly T[], seed: number): T { return list[seed % list.length] as T } export function makePerson(seed: number): Person { const first = pick(FIRST, seed) const last = pick(LAST, seed * 31 + 7) const dept = pick(DEPARTMENTS, seed * 7) return { id: `P${String(seed).padStart(4, '0')}`, name: `${first}${last}`, email: `user${seed}@movk.dev`, department: dept, role: pick(ROLES, seed * 3), level: pick(LEVELS, seed * 11), status: pick(STATUS, seed * 13), salary: 8000 + (seed * 257) % 50000, joinedAt: new Date(2018 + (seed % 7), seed % 12, 1 + (seed % 27)).toISOString().slice(0, 10), address: pick(ADDRESSES, seed * 17), bio: pick(BIO_TEMPLATES, seed * 19) } } export function makePeople(count: number, offset = 0): Person[] { return Array.from({ length: count }, (_, i) => makePerson(offset + i + 1)) } export function makePeopleTree(rootCount = 5, childPerRoot = 3, depth = 1): Person[] { const build = (seed: number, level: number): Person => { const person = makePerson(seed) if (level >= depth) return person return { ...person, role: '团队负责人', level: undefined, children: Array.from({ length: childPerRoot }, (_, j) => build(seed * 100 + j + 1, level + 1)) } } return Array.from({ length: rootCount }, (_, i) => build(i + 1, 0)) } ``` ## API ### Props ```ts /** * Props for the MDataTable component */ interface MDataTableProps { /** * 行唯一标识字段,自动派生 getRowId;与 getRowId 同传时后者优先 */ rowKey?: string & {} | keyof T & string | undefined; columns?: DataTableColumn[] | undefined; loading?: boolean | undefined; /** * 加载中且无数据时显示的骨架行数,`0` 时沿用 UTable 默认的加载样式;`loading` 插槽优先 * @default 5 */ skeletonRows?: number | undefined; /** * 在表格上方的工具栏显示列设置面板(显隐与拖拽排序) * @default false */ columnSettings?: boolean | undefined; /** * 设置后将列可见性、顺序、宽度、固定与每页条数持久化到 localStorage,值作为存储 key */ persistKey?: string | undefined; /** * 服务端全量 CSV 下载回调,应使用应用当前的外部筛选条件及表格传入的查询条件 */ serverCsvExport?: (context: DataTableServerCsvContext): void | Promise | undefined; /** * 斑马纹 * @default false */ stripe?: boolean | undefined; /** * 纵向边框,传对象可定制 color/width/style * @default false */ bordered?: boolean | { color?: string | undefined; width?: string | undefined; style?: "solid" | "dashed" | "dotted" | "double" | undefined; } | undefined; /** * 表格宽度由列宽内容决定(w-fit) * @default false */ fitContent?: boolean | undefined; /** * 空值占位符 * @default '-' */ emptyCell?: string | false | (props: CellContext): any | undefined; /** * 启用列固定按钮,传函数可按列动态决定 * @default false */ pinable?: boolean | ((col: DataTableDataColumn) => boolean) | undefined; pinButtonProps?: ButtonProps | (ctx: DataTablePinButtonContext): ButtonProps | undefined; /** * 启用列排序,传函数可按列动态决定 * @default false */ sortable?: boolean | ((col: DataTableDataColumn) => boolean) | undefined; sortButtonProps?: ButtonProps | (ctx: DataTableSortButtonContext): ButtonProps | undefined; /** * 全局 action 按钮 props,与列级 action.buttonProps 深度合并,列级优先 */ actionButtonProps?: ButtonProps | (ctx: DataTableActionButtonContext): ButtonProps | undefined; /** * 行内最多展示多少 action 按钮,超出折叠到 overflow * @default 3 */ actionsMaxInline?: number | undefined; actionsOverflowTrigger?: ButtonProps | (ctx: CellContext): ButtonProps | undefined; /** * 启用列宽拖拽,传函数可按列动态决定 * @default false */ resizable?: boolean | ((col: DataTableDataColumn) => boolean) | undefined; /** * - 'onChange' 拖动中实时重排 * - 'onEnd' 释放后才更新 * @default 'onChange' */ columnResizeMode?: "onChange" | "onEnd" | undefined; /** * 单元格内边距密度 */ density?: "compact" | "normal" | "comfortable" | { th?: string | ((cell: Header) => string) | undefined; td?: string | ((cell: Cell) => string) | undefined; } | undefined; meta?: TableMeta | undefined; rowClass?: string | (row: T): string | undefined; rowStyle?: string | Record | (row: T): string | Record | undefined; /** * 单元格溢出 Tooltip:true 单行 / number 多行 / false 禁用 / 函数 动态 * @default false */ tooltip?: number | false | true | (ctx: CellContext): number | boolean | undefined; tooltipProps?: OmitByKey | undefined; /** * 单元格文本截断:true 单行 / number 多行 / false 禁用 / 函数 动态 * @default true */ truncate?: number | false | true | (ctx: CellContext): number | boolean | undefined; sortingOptions?: Omit, "getSortedRowModel" | "onSortingChange"> | undefined; columnSizingOptions?: Omit | undefined; columnPinningOptions?: Omit | undefined; rowSelectionOptions?: Omit, "onRowSelectionChange"> | undefined; /** * 子行字段名,设置后启用树形模式 */ childrenKey?: string & {} | keyof T & string | undefined; /** * 树形缩进:number 每层缩进 px / string CSS 值 / 函数 动态返回 CSS * @default '1rem' */ indentSize?: string | number | (ctx: CellContext): string | undefined; /** * 树形模式下的默认展开行为,仅在未提供 expanded / expandedKeys 时生效。true 展开全部父级行,number 展开 depth 小于该值的父级行,函数按行与深度自定义 * @default false */ defaultExpanded?: number | false | true | (row: T, depth: number): boolean | undefined; expandedOptions?: Omit, "getExpandedRowModel" | "onExpandedChange"> | undefined; /** * @default false */ expandOnRowClick?: boolean | undefined; /** * @default false */ selectOnRowClick?: boolean | undefined; /** * 可见列白名单(数组形) */ columnVisibilityKeys?: string[] | undefined; /** * 隐藏列黑名单(数组形),与 columnVisibilityKeys 互斥,同传时白名单优先 */ columnVisibilityExcludeKeys?: string[] | undefined; /** * 选中行 id 列表(数组形) */ rowSelectionKeys?: string[] | undefined; /** * 展开行 id 列表(数组形) */ expandedKeys?: string[] | undefined; onSelect?: (e: Event, row: TableRow): void | undefined; onHover?: (e: Event, row: TableRow | null): void | undefined; onRowContextmenu?: (e: Event, row: TableRow): void | ((e: Event, row: TableRow) => void)[] | undefined; /** * 分页配置,透传给 TanStack / UTable * - 客户端分页:传入即启用,自动注入 getPaginationRowModel * - 服务端分页:manualPagination=true 并提供 rowCount 或 pageCount */ paginationOptions?: Omit | undefined; /** * 粘性表头 * @default true */ sticky?: boolean | "header" | "footer" | undefined; paginationUi?: DataTablePaginationUi & { ui?: { root?: SlotClass; summary?: SlotClass; summaryText?: SlotClass; selectedCount?: SlotClass; actions?: SlotClass; pageSizeSelect?: SlotClass; pagination?: SlotClass; } | undefined; } | undefined; /** * 触底加载回调,传入即启用无限滚动模式(自动隐藏内置分页、async 期间派生 loading) */ loadMore?: (): void | Promise | undefined; /** * `loadMore` 返回的 Promise 被拒绝时调用;缺省时输出到控制台 */ onLoadMoreError?: (error: unknown): void | undefined; /** * 是否还能加载更多 * @default true */ canLoadMore?: boolean | undefined; /** * 触发 loadMore 的距底像素阈值 * @default 100 */ loadMoreDistance?: number | undefined; ui?: Record & { wrapper?: SlotClass; toolbar?: SlotClass; skeleton?: SlotClass; skeletonRow?: SlotClass; base?: SlotClass; tbody?: SlotClass; th?: SlotClass; td?: SlotClass; root?: SlotClass; caption?: SlotClass; thead?: SlotClass; tfoot?: SlotClass; tr?: SlotClass; separator?: SlotClass; empty?: SlotClass; loading?: SlotClass; } | undefined; /** * The element or component this component should render as. * @default 'div' */ as?: any; data?: readonly T[] | undefined; caption?: string | undefined; /** * Enable virtualization for large datasets. * Note: row pinning is not supported when virtualization is enabled. * @default false */ virtualize?: boolean | (Partial, "count" | "estimateSize" | "overscan">> & { getScrollElement?: (() => Element | null) | undefined; overscan?: number | undefined; estimateSize?: number | ((index: number) => number) | undefined; }) | undefined; /** * The text to display when the table is empty. * @default t('table.noData') */ empty?: string | undefined; /** * @default 'primary' */ loadingColor?: "primary" | "secondary" | "info" | "success" | "warning" | "error" | "important" | "neutral" | undefined; /** * @default 'carousel' */ loadingAnimation?: "carousel" | "carousel-inverse" | "swing" | "elastic" | undefined; /** * Use the `watchOptions` prop to customize reactivity (for ex: disable deep watching for changes in your data or limiting the max traversal depth). This can improve performance by reducing unnecessary re-renders, but it should be used with caution as it may lead to unexpected behavior if not managed properly. * @default { deep: true } */ watchOptions?: WatchOptions | undefined; globalFilterOptions?: Omit, "onGlobalFilterChange"> | undefined; columnFiltersOptions?: Omit, "getFilteredRowModel" | "onColumnFiltersChange"> | undefined; visibilityOptions?: Omit | undefined; groupingOptions?: Omit | undefined; rowPinningOptions?: Omit, "onRowPinningChange"> | undefined; facetedOptions?: FacetedOptions | undefined; state?: Partial | undefined; onStateChange?: (updater: Updater): void | undefined; renderFallbackValue?: any; /** * An array of extra features that you can add to the table instance. */ _features?: TableFeature[] | undefined; /** * Set this option to override any of the `autoReset...` feature options. */ autoResetAll?: boolean | undefined; /** * Set this option to `true` to output all debugging information to the console. */ debugAll?: boolean | undefined; /** * Set this option to `true` to output cell debugging information to the console. */ debugCells?: boolean | undefined; /** * Set this option to `true` to output column debugging information to the console. */ debugColumns?: boolean | undefined; /** * Set this option to `true` to output header debugging information to the console. */ debugHeaders?: boolean | undefined; /** * Set this option to `true` to output row debugging information to the console. */ debugRows?: boolean | undefined; /** * Set this option to `true` to output table debugging information to the console. */ debugTable?: boolean | undefined; /** * Default column options to use for all column defs supplied to the table. */ defaultColumn?: Partial & StringHeaderIdentifier> | Partial & IdIdentifier> | Partial & StringHeaderIdentifier> | Partial & IdIdentifier> | Partial & Partial> | Partial & Partial>> | Partial & StringHeaderIdentifier> | Partial & IdIdentifier> | undefined; /** * This optional function is used to derive a unique ID for any given row. If not provided the rows index is used (nested rows join together with `.` using their grandparents' index eg. `index.index.index`). If you need to identify individual rows that are originating from any server-side operations, it's suggested you use this function to return an ID that makes sense regardless of network IO/ambiguity eg. a userId, taskId, database ID field, etc. */ getRowId?: (originalRow: T, index: number, parent?: Row | undefined): string | undefined; /** * This optional function is used to access the sub rows for any given row. If you are using nested rows, you will need to use this function to return the sub rows object (or undefined) from the row. */ getSubRows?: (originalRow: T, index: number): T[] | undefined | undefined; /** * Use this option to optionally pass initial state to the table. This state will be used when resetting various table states either automatically by the table (eg. `options.autoResetPageIndex`) or via functions like `table.resetRowSelection()`. Most reset function allow you optionally pass a flag to reset to a blank/default state instead of the initial state. * * Table state will not be reset when this object changes, which also means that the initial state object does not need to be stable. */ initialState?: InitialTableState | undefined; /** * This option is used to optionally implement the merging of table options. */ mergeOptions?: (defaultOptions: TableOptions, options: Partial>): TableOptions | undefined; cellpadding?: string | number | undefined; cellspacing?: string | number | undefined; summary?: string | undefined; width?: string | number | undefined; pagination?: PaginationState | undefined; columnVisibility?: VisibilityState | undefined; columnPinning?: ColumnPinningState | undefined; columnSizing?: ColumnSizingState | undefined; rowSelection?: RowSelectionState | undefined; /** * @default { top: [], bottom: [] } */ rowPinning?: RowPinningState | undefined; /** * @default [] */ sorting?: SortingState | undefined; columnOrder?: ColumnOrderState | undefined; expanded?: true | Record | undefined; } ``` ### Emits ```ts /** * Emitted events for the MDataTable component */ interface MDataTableEmits { update:pagination: (payload: [value: PaginationState | undefined]) => void; update:columnVisibility: (payload: [value: VisibilityState | undefined]) => void; update:columnPinning: (payload: [value: ColumnPinningState | undefined]) => void; update:columnSizing: (payload: [value: ColumnSizingState | undefined]) => void; update:rowSelection: (payload: [value: RowSelectionState | undefined]) => void; update:rowPinning: (payload: [value: RowPinningState]) => void; update:sorting: (payload: [value: SortingState]) => void; update:columnOrder: (payload: [value: ColumnOrderState | undefined]) => void; update:expanded: (payload: [value: ExpandedState | undefined]) => void; update:columnVisibilityKeys: (payload: [value: string[] | undefined]) => void; update:columnVisibilityExcludeKeys: (payload: [value: string[] | undefined]) => void; update:rowSelectionKeys: (payload: [value: string[] | undefined]) => void; update:expandedKeys: (payload: [value: string[] | undefined]) => void; } ``` ### Slots ```ts /** * Slots for the MDataTable component */ interface MDataTableSlots { expanded(): any; empty(): any; loading(): any; caption(): any; body-top(): any; body-bottom(): any; pagination(): any; pagination-summary(): any; pagination-actions(): any; /** * 表格上方工具栏;开启 `columnSettings` 时默认渲染列设置按钮 */ toolbar(): any; } ``` 除上述具名插槽外,还支持按列 id 命名的动态插槽 `#-header`、`#-cell`、`#-footer`,详见[列配置 · 表头与单元格插槽](https://nuxt.mhaibaraai.me/docs/data-table/columns#%E8%A1%A8%E5%A4%B4%E4%B8%8E%E5%8D%95%E5%85%83%E6%A0%BC%E6%8F%92%E6%A7%BD)。 ### Expose 通过 [`useTemplateRef`](https://vuejs.org/api/composition-api-helpers.html#usetemplateref) 访问类型化的组件实例(`DataTableExposed`)。 | Name | Type | | --- | --- | | `tableRef` | `HTMLTableElement \| null`
原生 table 元素 | | `tableApi` | `Table \| null`
TanStack Table 实例 | | `el` | `HTMLElement \| null`
UTable 根元素(滚动容器) | | `scrollToTop(options?)` | `void`
滚动到顶部 | | `clearSelection()` | `void`
清空行选择 | | `expandToDepth(depth)` | `void`
展开到指定层级,`depth=0` 等价收起全部 | | `collapseAll()` | `void`
收起全部行 | | `treeSelection` | `TreeSelectionResult`
树形选中派生:`selected`、`leaves`、`parents`、`halfSelected`、`strictlyChecked` | ### 列类型 `columns` 数组的每一项是 `DataTableColumn`,按形态区分: | 类型 | 判定 | 说明 | | --- | --- | --- | | `DataTableDataColumn` | 含 `accessorKey` | 数据列:排序、固定、截断、tooltip、可见性、自定义渲染 | | `DataTableGroupColumn` | 含 `children` | 分组表头 | | `DataTableSelectionColumn` | `type: 'selection'` | 选择列(单/多选、树形策略) | | `DataTableIndexColumn` | `type: 'index'` | 索引列 | | `DataTableExpandColumn` | `type: 'expand'` | 展开列 | | `DataTableRowPinningColumn` | `type: 'row-pinning'` | 行固定列 | | `DataTableActionsColumn` | `type: 'actions'` | 操作列 | ### 事件处理类型 事件处理器使用以下类型,参数由 contextual typing 推断: | 类型 | 用途 | | --- | --- | | `DataTableSelectHandler` | `@select` | | `DataTableHoverHandler` | `@hover` | | `DataTableContextmenuHandler` | `@row-contextmenu` | ## Theme ::component-theme{slug="DataTable"} :: ## Changelog See commit history for [src/runtime/components/介绍.vue](https://github.com/mhaibaraai/movk-nuxt/commits/main/src/runtime/components/介绍.vue). # 外观 > 组件样式覆盖、分页样式覆盖、斑马纹与边框、视觉密度、内容自适应、空值占位与粘性表头。 ## `ui` 组件样式覆盖 `ui` prop 接收 slot class 映射,与主题深度合并,定制 `root`、`th`、`td`、`tbody` 等局部样式: ```vue [DataTableUiOverrideExample.vue] ``` ## `paginationUi` 分页样式覆盖 `paginationUi.ui` 接收 Pagination 主题 slots,可重写 `root`、`summary`、`actions`、`selectedCount` 等局部 class;`paginationUi` 还可配置 `show`、`pageSizes`: ```vue [DataTablePaginationUiExample.vue] ``` ## 斑马纹与边框 `stripe` 控制偶数行底色;`bordered` 支持布尔与对象形态,对象形态通过 `color`/`width`/`style` 自定义纵向边框: ```vue [DataTableStripeBorderedExample.vue] ``` ## `density` 视觉密度 `density` 切换 `compact`、`normal`、`comfortable` 三档单元格内边距预设: ```vue [DataTableDensityExample.vue] ``` ## `fitContent` 内容自适应宽度 `fitContent` 让表格宽度由列宽决定,不再撑满父容器,适合工具型紧凑表格: ```vue [DataTableFitContentExample.vue] ``` ## `emptyCell` 空值占位 `emptyCell` 支持字符串、函数模板(返回 VNode)与 `false`,分别用于自定义文本、自定义节点与完全关闭。列级 `emptyCell` 优先于全局: ```vue [DataTableEmptyCellVariantsExample.vue] ``` ## `sticky` 粘性表头 `sticky` 默认开启,关闭后表头随内容滚动;需配合受限高度的滚动容器(如 `ui.root: 'max-h-[40vh]'`): ```vue [DataTableStickyExample.vue] ``` # 列配置 > 数据列的固定、排序、列固定切换、列宽拖拽、文本截断、Tooltip、可见性与函数式配置。 ## `fixed` 固定列 `column.fixed` 把列贴到表格两侧,横向滚动时保持可见: ```vue [DataTableFixedExample.vue] ``` ## `children` 分组表头 通过 `children` 定义分组列(`DataTableGroupColumn`),形成多级表头: ```vue [DataTableGroupExample.vue] ``` ## `sortable` 列排序 全局 `sortable` 启用所有数据列点击表头排序;列级 `sortable` 反向覆盖单列(如 `sortable: false` 锁定不可排序): ```vue [DataTableSortableExample.vue] ``` ## `pinable` 列固定切换 全局 `pinable` 让用户点表头图钉在 `left`、`right`、`none` 间循环;列级 `pinable` 优先级更高,可锁住强制位: ```vue [DataTablePinableExample.vue] ``` ## `resizable` 列宽拖拽 全局 `resizable` 给所有数据列加拖拽手柄;列级 `resizable: false` 锁定单列宽度。`columnResizeMode` 控制 `onChange`(拖动中实时重排)或 `onEnd`(释放后更新): ```vue [DataTableResizableExample.vue] ``` ## `size` / `minSize` / `maxSize` 列宽 `size` 设定固定列宽(数值或预设 `xs`–`xl`)。不设 `size` 而仅给 `minSize` / `maxSize` 时,列宽由内容自适应:`minSize` 是自适应与拖拽的下限;`maxSize` 是可拖拽到的最大宽度。已设 `size` 的列会被 `minSize` / `maxSize` 双向收敛。 ```ts const columns: DataTableColumn[] = [ { accessorKey: 'name', header: '姓名', minSize: 120 }, // 自适应,不小于 120 { accessorKey: 'bio', header: '简介', maxSize: 240 }, // 自适应,拖拽不超过 240 { accessorKey: 'id', header: '工号', size: 'sm' } // 固定预设宽 120 ] ``` > [!NOTE] > > 表格采用 > > table-layout: auto > > 并撑满容器,自适应列的内容宽度可能超过 > > maxSize > > (auto 布局忽略单元格 > > max-width > > )。因此对自适应列, > > maxSize > > 仅约束拖拽上限;要严格固定列宽请改用 > > size > > 。 > [!NOTE] > > 固定列( > > fixed > > )需要确定宽度参与 sticky 偏移计算,因此默认固定为 > > size > > 。仅当某一侧只有一个固定列(贴近滚动区的内侧固定列)时,该列才支持按内容自适应——此时设 > > minSize > > / > > maxSize > > 即可让它随内容撑开(典型如右侧唯一的操作列)。 ## 文本截断与 Tooltip `truncate` 控制纯截断(`true` 单行 / `number` 多行 / `false` 禁用 / 函数动态);`tooltip` 自带相同行数的截断,并在溢出时浮出完整内容。两者不需同时配置: ```vue [DataTableTruncateExample.vue] ``` ## 列可见性 `column.visibility` 设默认显隐;`columnVisibilityKeys`(白名单)与 `columnVisibilityExcludeKeys`(黑名单)互斥,同传时白名单优先: ```vue [DataTableVisibilityExample.vue] ``` ## `columnSettings` 列设置 开启列设置后可调整列显隐与顺序。`persistKey` 将列设置和每页条数保存在浏览器。`v-model:columnOrder` 可从外部控制顺序,`resetColumns()` 恢复默认列设置。 ```vue [DataTableColumnSettingsExample.vue] ``` ## 函数式配置 `sortable`、`pinable`、`resizable` 接受 `(col) => boolean`,`truncate`、`tooltip` 接受 `(ctx) => boolean | number`,一次声明替代逐列布尔,并可按字段或单元格上下文动态决定: ```vue [DataTableFunctionalExample.vue] ``` > [!TIP] > > 列级 prop 优先级始终高于全局 prop。推荐用「全局开 + 个别列关」或「全局关 + 个别列开」的对照方式表达差异。 ## 表头与单元格插槽 除了在 `columns` 里配置 `header` / `cell`,也可以按列 id 使用插槽渲染。列 id 即数据列的 `accessorKey`,特殊列则是 `__selection`、`__index`、`__expand`、`__row_pinning`、`__actions`: | 插槽 | 作用域类型 | 说明 | | --- | --- | --- | | `#-header` | `HeaderContext` | 替换该列表头标签 | | `#-cell` | `CellContext` | 替换该列单元格内容 | | `#-footer` | `HeaderContext` | 替换该列表尾内容 | ```vue [DataTableColumnSlotsExample.vue] ``` > [!NOTE] > > #-header > > 只替换 > > 标签位 > > , > > sortable > > 、 > > pinable > > 、 > > resizable > > 生成的排序按钮、图钉按钮与列宽拖拽手柄仍会保留在表头内,无需自行渲染。 > [!WARNING] > > #-cell > > 整体替换单元格内容,该列的 > > truncate > > 、 > > tooltip > > 、 > > emptyCell > > 不再生效,需要时请在插槽内自行处理。分组表头( > > children > > )的 id 由 TanStack 内部拼接,不支持插槽覆写,请用 > > header > > 配置。 # 特殊列 > 选择列、索引列、行固定列与操作列的配置,含树形选择策略、动态按钮与二次确认。 ## 概述 数据列用 `accessorKey` 绑定字段;特殊列通过 `type` 区分,无需 `accessorKey`: | `type` | 用途 | | --- | --- | | `selection` | 行选择(单选/多选,树形支持级联策略) | | `index` | 行序号 | | `expand` | 树形展开(见[树形数据](https://nuxt.mhaibaraai.me/docs/data-table/tree)) | | `row-pinning` | 行固定到顶部/底部 | | `actions` | 行操作按钮 | > [!TIP] > > 所有特殊列同样支持 > > visibility > > 、 > > pinable > > 、 > > resizable > > 、 > > fixed > > 、 > > size > > 、 > > align > > 。 ## 选择列 ### `mode` 单选 / 多选 `mode` 作用:默认 `multiple` 自动渲染表头与单元格复选框、`v-model:row-selection` 同步选中 id 字典;`single` 关闭多选并显示自定义 `header`,选中态始终至多保留一个: ```vue [DataTableSelectionExample.vue] ``` ### `strategy` 树形选择策略 `strategy` 在树形模式(`children-key`)下生效,控制父子勾选关系:`cascade` 父子级联、`isolated` 独立勾选、`leaf` 仅叶子可选(父节点展示为派生态): ```vue [DataTableSelectionStrategyExample.vue] ``` ### `checkboxProps` 函数式配置 `checkboxProps` 接收上下文返回 props:可按 `scope` 区分表头/单元格、按 `isLeafAggregate` 区分父行派生态、按行数据派生 `disabled`: ```vue [DataTableSelectionCheckboxPropsExample.vue] ``` ### rowSelectionKeys 与 treeSelection `v-model:row-selection-keys` 用数组形态外部受控;组件 expose 的 `treeSelection` 派生 `leaves`、`parents`、`halfSelected`、`strictlyChecked` 等业务视图(通过 `useTemplateRef` 访问): ```vue [DataTableSelectionKeysExample.vue] ``` ## 索引列 `type: 'index'` 默认渲染 `#` 表头,行号随排序、分页自动重新计算,可通过 `header` 自定义: ```vue [DataTableIndexExample.vue] ``` ## 行固定列 ### `position` 顶部 / 底部固定 `type: 'row-pinning'` 的 `position` 取 `top` 或 `bottom`,把行钉到表头或表尾,`v-model:row-pinning` 暴露 `top`、`bottom` 两组 id: ```vue [DataTableRowPinningExample.vue] ``` ### `buttonProps` 动态固定按钮 `buttonProps` 接收 `pinned` 状态返回 `icon`、`color`、`variant`,区分已固定与未固定行: ```vue [DataTableRowPinningDynamicExample.vue] ``` ## 操作列 ### `maxInline` 内联与折叠 `maxInline` 控制平铺按钮数,超出部分折叠到溢出菜单;`action.divider` 在菜单中插入分隔线: ```vue [DataTableActionsInlineExample.vue] ``` ### `actions` 数组与函数式 `actions` 既可传静态数组,也可传 `(ctx) => DataTableAction[]` 按行派生: ```vue [DataTableActionsFunctionalExample.vue] ``` ### 异步动作自动 loading `onClick` 返回 Promise 时按钮自动进入 loading,期间禁用并阻止重复触发(仅作用于内联按钮): ```vue [DataTableActionsAsyncExample.vue] ``` ### `confirm` 二次确认 `confirm: true` 在执行前弹出 MessageBox;`confirmProps` 可动态返回 `title`、`type`、`description`、`confirmLabel`: ```vue [DataTableActionsConfirmExample.vue] ``` ### 动态 disabled 与 visibility `action.disabled` 与 `action.visibility` 接受布尔或 `(ctx) => boolean`,按行派生禁用或隐藏: ```vue [DataTableActionsDynamicStateExample.vue] ``` ## 特殊列的共享字段 `selection`、`index`、`row-pinning`、`actions` 列与数据列一样支持 `visibility`、`pinable`、`resizable`、`size`、`minSize`、`maxSize`、`align`、`fixed`。特殊列默认固定宽 60;给 `minSize` / `maxSize`(且不设 `size`)即改为按内容自适应——`minSize` 为下限、`maxSize` 为拖拽上限。右侧唯一的操作列(`fixed: 'right'`)设 `minSize` 可让其随按钮数撑开,详见[数据列的列宽规则](https://nuxt.mhaibaraai.me/docs/data-table/columns)。 ```vue [DataTableSpecialSharedExample.vue] ``` # 行为与交互 > 行选择、展开详情、点击行为、动态行样式、悬停、右键菜单与编程式控制。 ## `rowKey` 行标识 `row-key` 指定行唯一标识字段,自动派生 TanStack 的 `getRowId`,是选择、展开、树形等功能正确追踪行的基础。设置后选中态、展开态均按业务 id 而非数组下标追踪——打乱 `data` 顺序后,选中行仍指向同一条记录: ```vue [DataTableRowKeyExample.vue] ``` ## 基础行选择 `v-model:row-selection` 双向同步选中 id 集合;`@select` 事件返回当前点击行(`DataTableSelectHandler`): ```vue [DataTableRowSelectionExample.vue] ``` ## 行展开与详情槽位 `v-model:expanded` 控制展开行 id,`#expanded` 槽位渲染详情区域: > [!NOTE] > > type: 'expand' > > 列表头默认渲染「全部展开/收起」按钮,可通过 > > toggleAll: false > > 关闭 ```vue [DataTableRowExpandExample.vue] ``` ## 点行触发选择与展开 `select-on-row-click` 整行点击切换选中,`expand-on-row-click` 整行点击切换展开,两者可独立开启: ```vue [DataTableRowClickExample.vue] ``` ## 动态行样式 `row-class` 接受 `(row) => string`,`row-style` 接受 `(row) => string | Record`,按行数据派生类名与内联样式: ```vue [DataTableRowStyleExample.vue] ``` ## 行悬停追踪 `@hover` 在进入和离开行时触发(`DataTableHoverHandler`),第二参数为 `TableRow` 或 `null`,可用于联动外部高亮: ```vue [DataTableRowHoverExample.vue] ``` ## 行右键菜单 `@row-contextmenu` 拦截右键事件(`DataTableContextmenuHandler`),回调入参含原始 `MouseEvent` 与目标行,可阻止默认菜单并弹出自定义操作: ```vue [DataTableRowContextmenuExample.vue] ``` ## 编程式控制 通过 `useTemplateRef` 拿到组件实例,调用 expose 的 `clearSelection()` 清空选中、`scrollToTop()` 滚回顶部: ```vue [DataTableRowImperativeExample.vue] ``` # 树形数据 > 通过 childrenKey 启用树形表格,配置展开、级联选择策略、缩进与选中结果读取。 ## 树形数据基础 设置 `children-key` 即启用树形模式,配合 `row-key` 派生行 id、`expand` 列渲染折叠按钮。父级缺失字段(如职级)可由 `emptyCell` 占位: ```vue [DataTableTreeBasicExample.vue] ``` ## `strategy` 级联选择策略 `selection` 列的 `strategy` 决定父子勾选联动:`cascade` 父子级联、`isolated` 父子独立、`leaf` 仅叶子可勾(父节点展示为子孙派生态): ```vue [DataTableTreeStrategyExample.vue] ``` ## `mode` 单选与多选 `mode: 'single'` 时整树仅单行勾选(通常配合 `isolated`);`multiple` 时配合 `strategy` 联动: ```vue [DataTableTreeModeExample.vue] ``` ## 选中结果读取 `v-model:row-selection-keys` 双向同步选中 id 数组;组件 expose 的 `treeSelection` 派生 `leaves`、`parents`、`halfSelected`、`strictlyChecked` 四类业务视图,并提供 `clearSelection()`: ```vue [DataTableTreeResultExample.vue] ``` ## `indentSize` 树形缩进 `indentSize` 支持字符串、数字(px)与函数三种形态,函数形态可按 `row.depth` 等上下文动态调整: ```vue [DataTableTreeIndentExample.vue] ``` ## `defaultExpanded` 默认展开 `default-expanded` 在未提供 `expanded` / `expanded-keys`(受控优先)时决定初始展开:`true` 展开全部父级行、`number` 展开 `depth` 小于该值的父级行(与 `expandToDepth(n)` 同义)、函数 `(row, depth) => boolean` 按行与深度自定义,无需手写收集父级 id: ```vue [DataTableTreeDefaultExpandExample.vue] ``` ## 展开行为控制 `expand` 列的 `buttonProps` 与 `toggleAllButtonProps` 分别定制单元格与表头按钮(接收 `isExpanded`/`isAllExpanded`);`expand-on-row-click` 整行触发展开;expose 的 `expandToDepth(n)` 按层展开、`collapseAll()` 收起全部,`v-model:expanded-keys` 同步展开 id: ```vue [DataTableTreeExpandExample.vue] ``` # 分页与加载更多 > 客户端自动分页、服务端手动分页与加载状态,以及触底加载、无限滚动的实用参数。 ## CSV 导出 `exportCsv()` 默认导出已加载的过滤排序结果。`rows: 'page'` 导出当前可见页,`rows: 'selected'` 导出已加载的选中行。手动分页需要全部匹配行时,提供 `serverCsvExport`,再调用 `await table.exportServerCsv()`。回调接收列 ID、文件名、表格排序和筛选条件,可和外部搜索条件一同传给后端。Nuxt 可复用 `useDownloadWithProgress`,纯 Vue 可传入自己的下载函数。 加载中且无数据时,`skeletonRows` 设置骨架行数,默认 5。自定义 `loading` 插槽优先。 ## 客户端自动分页 传入 `v-model:pagination` 即触发自动分页,组件在本地切片数据并渲染默认分页栏: ```vue [DataTableClientPaginationExample.vue] ``` ## 服务端手动分页 `paginationOptions.manualPagination` 设为 `true` 并提供 `rowCount`,由调用方接管分页——只把当前页数据传给 `data`。下例用本地切片模拟服务端,实际场景中应在 `pagination` 变化时请求后端: ```vue [DataTableServerPaginationExample.vue] ``` > [!TIP] > > 配合 > > :loading > > 、 > > :sorting-options="{ manualSorting: true }" > > 与 > > v-model:sorting > > 可实现服务端排序;搜索时把 > > pagination.pageIndex > > 重置为 0。 ## 页数形态 后端只返回总页数而非总条数时,改用 `paginationOptions.pageCount` 直接指定总页数: ```vue [DataTablePageCountPaginationExample.vue] ``` ## 每页条数切换 `paginationUi.pageSizes` 长度大于 1 时显示每页条数切换器: ```vue [DataTablePageSizesPaginationExample.vue] ``` ## 分页摘要与文案 `v-model:row-selection` 配合 `row-key` 联动已选计数;`paginationUi` 的 `showSelectedCount`、`showRowRange`、`text` 控制摘要区显示与文案: ```vue [DataTablePaginationSummaryExample.vue] ``` ## 透传分页组件 `paginationUi.paginationProps` 透传 `UPagination` 的 `showEdges`、`siblingCount` 等;`pageSizeSelectProps` 透传每页条数选择器属性: ```vue [DataTablePaginationPassthroughExample.vue] ``` ## 分页栏槽位 `#pagination-summary` 与 `#pagination-actions` 分别替换摘要区与操作区: ```vue [DataTablePaginationSlotsExample.vue] ``` `#pagination` 槽位接收完整分页状态(`page`/`pageCount`/`from`/`to`/`setPage` 等),整条替换默认分页栏: ```vue [DataTablePaginationFullExample.vue] ``` ## `loading` 加载状态 `loading` 透传给底层 `UTable` 显示加载态,适合首屏请求或切页等待: ```vue [DataTableLoadingExample.vue] ``` ## `loadMore` 触底加载 传入 `load-more` 回调即启用无限滚动模式(自动隐藏内置分页)。回调返回 Promise 时,组件在加载期间自动派生 `loading`: ```vue [DataTableLoadMoreExample.vue] ``` > [!NOTE] > > 需要一个受限高度的滚动容器(如 > > ui.root: 'h-[60vh]' > > )才能产生滚动并触发触底加载。 ## `canLoadMore` 终止加载 `can-load-more` 为 `false` 时停止触发,可独立于剩余数据强制暂停(如无更多数据、出错后停止): ```vue [DataTableLoadMoreCanLoadMoreExample.vue] ``` ## `loadMoreDistance` 触发阈值 `load-more-distance` 设置触发加载的距底像素阈值(默认 100),值越大越提前触发: ```vue [DataTableLoadMoreDistanceExample.vue] ``` ## 调用方接管 loading 若希望由调用方接管 loading,可让 `load-more` 同步返回(不交回 Promise)并自行传入 `:loading`,与自动派生形态对照: ```vue [DataTableLoadMoreManualLoadingExample.vue] ``` # 概览 > Nuxt 数据获取基础与 Movk Nuxt API 系统的核心概念和架构设计。 ## Nuxt 数据获取基础 Nuxt 提供三种数据获取方式,理解它们的区别有助于选择正确的 Movk Nuxt 封装。 - [`$fetch`](https://nuxt.com/docs/4.x/api/utils/dollarfetch) :底层 HTTP 客户端,基于 [ofetch](https://github.com/unjs/ofetch),在服务端和客户端均可运行。```ts // 用户点击时调用 -- 适合 $fetch async function handleSubmit() { const result = await $fetch('/api/login', { method: 'POST', body: { username, password } }) } ``` - [`useFetch`](https://nuxt.com/docs/4.x/api/composables/use-fetch):`useAsyncData` + `$fetch` 的语法糖封装```ts // 页面加载时获取数据 -- 适合 useFetch const { data: posts, status, error } = await useFetch('/api/posts') ``` - [`useAsyncData`](https://nuxt.com/docs/4.x/api/composables/use-async-data):最灵活的数据获取 composable。```ts // 聚合多个接口 -- 适合 useAsyncData const { data } = await useAsyncData('dashboard', async () => { const [users, stats] = await Promise.all([ $fetch('/api/users'), $fetch('/api/stats') ]) return { users, stats } }) ``` ## 关键参数详解 `useFetch`(以及 `useApiFetch`)的三个核心参数决定了请求的执行时机和行为。 ### `server` 控制是否在服务端执行数据获取。**默认 `true`**。 **行为对比:** - `server: true`(默认)-- SSR 时在服务端执行请求,数据通过 payload 传到客户端,客户端不再重复请求 - `server: false` -- 仅在客户端执行。首次加载时数据在 hydration 完成后才开始获取,`data` 初始为 `null` **使用场景:** - `server: true` -- SEO 相关数据、首屏需要展示的内容 - `server: false` -- 非 SEO 敏感数据(用户评论、个性化推荐、统计数据),减轻服务端负担 ```ts // 文章列表需要 SEO -- server: true(默认) const { data: posts } = await useApiFetch('/posts') // 评论数据不需要 SSR -- server: false const { data: comments } = useApiFetch('/comments', { server: false, lazy: true, }) ``` > [!NOTE] > > server: false > > 通常与 > > lazy: true > > 搭配使用,这正是 > > useClientApiFetch > > 的预设行为。 ### `lazy` 控制是否阻塞客户端导航。**默认 `false`**。 **行为对比:** - `lazy: false`(默认)-- 通过 Vue Suspense 阻塞导航,等数据返回后才完成路由切换。用户看不到 loading 状态 - `lazy: true` -- 不阻塞导航,页面立即显示,数据在后台获取。需要手动处理 loading 状态 **使用场景:** - `lazy: false` -- 页面核心数据,没有数据页面无法正常渲染 - `lazy: true` -- 次要数据、非首屏数据、可以先展示骨架屏的场景 ```ts // 核心数据 -- 阻塞导航等待数据(默认) const { data: article } = await useApiFetch
(`/articles/${id}`) // 次要数据 -- 不阻塞导航,后台加载 const { data: related, status } = useLazyApiFetch( `/articles/${id}/related` ) ``` ```vue ``` > [!NOTE] > > SSR 阶段 > > lazy > > 的行为与非 lazy 基本一致(都会等待数据返回),差异主要体现在 > > 客户端导航 > > 时。 ### `immediate` 控制是否在 composable 初始化时立即执行请求。**默认 `true`**。 **行为对比:** - `immediate: true`(默认)-- 创建时立即触发请求 - `immediate: false` -- 不自动请求,`status` 为 `idle`,需手动调用 `execute()` 触发 **使用场景:** - `immediate: true` -- 页面加载就需要的数据 - `immediate: false` -- 需要等待用户操作后才触发的请求 ```ts // 预定义表单提交请求,不自动执行 const { data, execute, status, error } = useApiFetch('/login', { method: 'POST', body: credentials, immediate: false, lazy: true, }) // 用户点击登录按钮时手动触发 async function handleLogin() { await execute() if (!error.value) { navigateTo('/dashboard') } } ``` > [!TIP] > > immediate: false > > 常与 > > lazy: true > > 搭配使用。如果只设 > > immediate: false > > 而不设 > > lazy: true > > ,Suspense 仍会等待(虽然请求从未发出),可能导致页面悬挂。 ## Movk Nuxt API 系统 Movk Nuxt 为每个端点创建一个包装 ofetch 的 API 客户端([`$api` 插件](https://nuxt.mhaibaraai.me/docs/api/api-plugin)),以及一组封装 `useFetch` 的 composable,在 Nuxt 原生数据获取能力之上提供统一的认证、业务检查、错误归一、Toast 提示等增强功能。 ```text nuxt.config.ts (movk.api 配置) | v api.factory.ts 插件 -- 按端点创建并缓存 $api 客户端 | v 端点客户端(每次调用:内置钩子在前、用户钩子在后组合,互不覆盖) ├── onRequest: 认证注入 -> debug 日志 -> movk:api:request hook ├── onResponse: 流内 JSON 还原 -> 业务检查 -> 数据解包 -> movk:api:response hook -> 成功 Toast └── 出口 catch: 归一为 ApiError -> 401 处理 -> movk:api:error hook -> 错误 Toast(重试结束后只上报一次) | v Composables ├── useApiFetch useFetch + $api (SSR/CSR 通用) ├── useLazyApiFetch lazy: true 预设 ├── useClientApiFetch server: false, lazy: true 预设 ├── useUploadWithProgress $api 管线 + XHR 适配器上报上传进度 ├── useDownloadWithProgress $api.raw 流式读取 + 下载进度 └── useApiStream $api.stream() + SSE 解析 + 中止 ``` 上传、下载、流式请求与 `useApiFetch` 走同一条客户端管线,端点请求头、认证、业务检查、错误分类与 hook 完全一致。 流式响应(SSE、二进制)不进业务检查与解包链路:`onResponse` 识别到可读流即整段短路, 由 [`useApiStream`](https://nuxt.mhaibaraai.me/docs/api/stream) 或 [`createChatTransport`](https://nuxt.mhaibaraai.me/docs/api/stream) 接手。 ### 多端点支持 支持配置多个 API 端点,每个端点可独立设置 baseURL、认证、Toast 和响应规则。通过 `endpoint` 选项或 `$api.use()` 切换端点。 > [!TIP] > See: /docs/getting-started/configuration#endpoints > > 了解端点配置选项 ### 自动认证 与 `nuxt-auth-utils` 集成。启用后,每次请求自动从 session 提取 token 并注入到请求头。支持嵌套路径(如 `user.accessToken`)和多种 token 格式(Bearer、Basic、Custom)。 > [!TIP] > See: /docs/getting-started/configuration#auth > > 了解认证配置选项 ### 业务状态码检查 `$api` 拦截器自动检查响应 `code` 是否在 `successCodes` 中,业务失败时抛出 `ApiError` 并显示 Toast。直接返回裸资源的端点可在端点 `response` 上关闭 `businessCheck`。 > [!TIP] > See: /docs/api/api-plugin#数据解包与业务校验 > > 查看业务校验与 > > businessCheck > > 的交互示例 ### 数据解包 `$api` 拦截器自动提取响应中 `dataKey`(默认 `data`)字段,泛型 `T` 直接对应业务数据类型。 > [!TIP] > See: /docs/api/api-plugin#数据解包与业务校验 > > 查看解包与 > > unwrap > > 的交互示例 ### 错误归一 所有失败(业务码、HTTP 4xx/5xx、网络中断、超时)统一为 `ApiError`(`NuxtError`),按 `error.data.kind` 区分场景;`useApiFetch` 的 `error` 与 `$api` 抛出的错误是同一对象。 > [!TIP] > See: /docs/api/use-api-fetch#错误分类 > > 查看错误分类示例 ### Toast 提示 请求成功/失败时自动显示 Toast 提示。支持四层配置优先级:请求级 > 端点级 > 全局级 > 内置默认值。可在任意层级禁用或自定义。 > [!TIP] > See: /docs/getting-started/configuration#toast > > 了解 Toast 配置选项 ### 401 未授权处理 收到 HTTP 401 或业务码 401 时(含上传 / 下载进度请求),默认自动清除 session 并跳转登录页。可通过 [API Hooks](https://nuxt.mhaibaraai.me/docs/api/hooks#movkapiunauthorized) 拦截并实现自定义逻辑(如 token 刷新)。 > [!TIP] > See: /docs/getting-started/configuration#auth > > 了解 401 处理配置选项 ## 从 v1 迁移到 v2 v2 把响应处理收敛到每个端点一个客户端,以下变更需要调整调用方代码: | 变更 | v1 | v2 | | --- | --- | --- | | 请求级开关改为正向命名 | `skipBusinessCheck: true` / `skipUnwrap: true` | `businessCheck: false` / `unwrap: false` | | `$api` 请求级选项不再包在 `context` 中 | `$api(url, { context: { toast: false } })` | `$api(url, { toast: false })` | | 裸资源端点在端点上声明 | 每个请求传两个 skip 开关 | `endpoints.x.response: { businessCheck: false, unwrap: false }` | | 所有失败统一为 `ApiError`(NuxtError) | `error.isBusinessError`、`error.response`;HTTP / 网络错误为 `FetchError` | `error.data.kind === 'business'`、`error.data.response`;HTTP、网络、超时同样是 `ApiError` | | `movk:api:error` 新增错误参数,只触发一次 | `(context)`,GET 5xx 重试时触发两次,网络错误不触发 | `(context, error)`,重试结束后触发一次,网络错误与超时同样触发 | | 上传超时选项改名 | `timeoutMs` | `timeout` | | 上传 / 下载请求头与 `$api` 同序叠加 | 用户 `headers` 覆盖 auth 头,且忽略端点 `publicHeaders` | 注入端点 `publicHeaders`;启用认证时 auth 头最后写入、优先级最高 | | 上传 / 下载关闭校验后仍解包 | `skipBusinessCheck` 返回原始响应体 | `businessCheck: false` 仍按 `dataKey` 解包,需要原始响应体时再传 `unwrap: false` | `$api` 中用户传入的 `onRequest` / `onResponse` 不再覆盖内置拦截器,v1 中依赖覆盖来绕过解包的写法需改为 `unwrap: false`。 # $api > 由 api.factory 插件创建的增强型 $fetch 实例,支持认证注入、数据解包、业务检查和多端点切换。 ## 介绍 `$api` 是通过 Nuxt 插件注入的全局 `$fetch` 实例,内置完整的拦截器链(认证注入、业务状态码检查、数据解包、Toast 提示)。它是所有 API composable(`useApiFetch`、`useLazyApiFetch` 等)的底层引擎。 ## 用法 ```ts const { $api } = useNuxtApp() // GET 请求(数据已自动解包) const users = await $api('/users') // POST 请求 const user = await $api('/users', { method: 'POST', body: { name: 'test', email: 'test@example.com' } }) // PUT 请求 const updated = await $api(`/users/${id}`, { method: 'PUT', body: { name: 'new-name' } }) // DELETE 请求 await $api(`/users/${id}`, { method: 'DELETE' }) ``` > [!NOTE] > > $api > > 返回的数据已经过拦截器自动解包(提取 > > dataKey > > 字段),泛型 > > T > > 直接对应业务数据类型。 ## 多端点切换 使用 `$api.use(endpoint)` 切换到指定端点: ```ts const { $api } = useNuxtApp() // 使用默认端点 const users = await $api('/users') // 切换到 admin 端点 const adminUsers = await $api.use('admin')('/users') // 保存端点引用,避免重复 use() const adminApi = $api.use('admin') const config = await adminApi('/config') const stats = await adminApi('/stats') ``` 端点实例内部有缓存机制,多次调用 `$api.use('admin')` 返回同一实例。 ### 切换并对照 baseURL `$api` 默认走 default 端点的 `baseURL`,`$api.use(name)` 切换到别名端点后请求改用对应 `baseURL`。下拉切换端点即可观察 `baseURL` 与返回随之变化: ```vue [ApiEndpointsExample.vue] ``` ### 命令式调用 脱离 `useFetch` 上下文,直接通过 `$api.use(name)` 取得端点实例并发起裸请求: ```vue [ApiEndpointsImperativeExample.vue] ``` ### 当前生效配置 `runtimeConfig.public.movkApi` 暴露端点列表与默认端点名,便于运行时调试: ```vue [ApiEndpointsRuntimeExample.vue] ``` > [!TIP] > See: /docs/getting-started/configuration#endpoints > > 了解如何配置多个 API 端点 ## 认证集成 启用 `auth` 且 `tokenSource` 为 `'session'`(默认)时,模块自动接入 `nuxt-auth-utils`:登录后从 `session[sessionTokenPath]` 读取 token,所有 `$api` 请求自动注入 `Authorization` 头;遇到 401 时按 `auth.unauthorized` 策略清理 session 或跳转登录页。 ### 当前 Session `useUserSession` 暴露的响应式 session;登录 / 登出后调用 `fetch()` 同步状态: ```vue [ApiAuthSessionExample.vue] ``` ### 调用受保护接口 `useApiFetch` 自动携带 Authorization 头访问 `/demo/protected`;未登录时返回 401: ```vue [ApiAuthProtectedExample.vue] ``` ### 401 处理策略 `auth.unauthorized` 控制重定向与 session 清理;docs 站点为便于演示关闭重定向: ```vue [ApiAuthUnauthorizedExample.vue] ``` ### 令牌注入格式 `headerName` + `tokenType` 决定最终请求头形态;后端 echo `authHeader` 字段供核对: ```vue [ApiAuthTokenInjectionExample.vue] ``` ## 数据解包与业务校验 `$api` 默认按 `response.dataKey` 抽取业务数据并按 `successCodes` 校验业务码;`unwrap` / `businessCheck` 两个开关可在全局、端点、请求三层声明,优先级为请求显式值 > 端点 > 全局。下拉切换模式观察返回结构差异: - `default`:按默认 `data` 字段抽取业务数据,调用方直接拿到去信封后的对象。 - `no-unwrap`:`unwrap: false` 不重写 `response._data`,保留完整 `code/message/data` 信封。 - `no-business-check`:legacy 接口未返回 `code` 字段,`businessCheck: false` 关闭校验后仍按 `dataKey` 解包出业务数据。 - `combined`:外部接口信封非标,两项同时关闭由调用方完全自处理响应。 ```vue [ApiUnwrapExample.vue] ``` ### 端点级声明 直接返回数组或裸对象(没有 `{ code, data }` 信封)是端点的固有属性,在端点 `response` 上声明一次,该端点的所有请求(含上传、下载、流式)都按此处理: ```ts [nuxt.config.ts] export default defineNuxtConfig({ movk: { api: { endpoints: { sensor: { baseURL: process.env.NUXT_SENSOR_URL, response: { businessCheck: false, unwrap: false } } } } } }) ``` ```ts // 直接拿到数组 const points = await $api.use('sensor')('/point-numbers') // 请求显式值优先:对该端点单次重新开启业务码校验 await $api.use('sensor')('/legacy', { businessCheck: true }) ``` > [!NOTE] > > 开启校验时,响应体为 > > null > > 、字符串、数组等非对象会判为业务失败( > > error.data.kind > > 为 > > business > > ),不会抛 > > TypeError > > 。 ## Toast 提示 `$api` 内置 Toast 提示,按 `toast.successCodes` 判定成功 / 失败;支持全局默认 + 请求级覆盖两层定制。下拉切换模式、配合「注入错误」开关观察成功 / 失败两条分支: - `default`:未传 `toast` 时继承全局配置,成功 / 错误均按默认样式弹出。 - `silent`:`toast: false` 关闭所有单次提示。 - `message`:`successMessage` / `errorMessage` 替换默认文案。 - `error-only`:`{ success: false }` 关闭成功提示但保留错误提示。 - `custom`:成功 / 错误分别覆盖 `color`、`icon` 等 ToastProps。 > [!NOTE] > > 全局或端点配置 > > toast.success.methods > > 可让成功提示只在 POST / PUT / PATCH / DELETE 等变更类请求上弹出;此时请求级 > > { success: { show: true } } > > 或 > > successMessage > > 仍可为单个 GET 请求开启提示。 ```vue [ApiToastExample.vue] ``` ## 在事件处理器中使用 事件处理器中使用 `$api` 是最常见的场景: ```vue ``` ## 在 useAsyncData 中使用 当需要聚合多个接口或做复杂数据处理时,在 `useAsyncData` 中使用 `$api`: ```ts const { $api } = useNuxtApp() // 聚合多个接口 const { data: dashboard } = await useAsyncData('dashboard', async () => { const [users, stats, recent] = await Promise.all([ $api('/users'), $api('/stats'), $api('/activity/recent') ]) return { users, stats, recent } }) ``` ### 封装自定义 composable ```ts [app/composables/useDashboard.ts] export function useDashboard() { const { $api } = useNuxtApp() return useAsyncData('dashboard', async () => { const [users, stats] = await Promise.all([ $api('/users'), $api('/stats') ]) return { users, stats } }) } ``` ### 业务操作 composable 对于删除、审批等写操作,将 `$api` 调用封装到独立的 composable 中,保持页面文件精简: ```ts [app/composables/useUserActions.ts] export function useUserActions() { const { $api } = useNuxtApp() async function remove(id: string) { await $api(`/users/${id}`, { method: 'DELETE' }) await refreshNuxtData() } async function create(data: CreateUserRequest) { return await $api('/users', { method: 'POST', body: data, }) } async function updateRole(id: string, role: UserRole) { return await $api(`/users/${id}/role`, { method: 'PUT', body: { role }, toast: { successMessage: '角色已更新' }, }) } return { remove, create, updateRole } } ``` ```vue [app/pages/users/index.vue] ``` ## 请求级配置 请求级选项与 ofetch 选项写在同一层,`$api`、`useApiFetch`、上传下载与流式请求写法一致: ```ts const { $api } = useNuxtApp() // 禁用 Toast await $api('/users', { toast: false }) // 自定义 Toast 消息 await $api('/users', { method: 'POST', body: formData, toast: { successMessage: '创建成功' } }) // 全局关闭成功提示时,单次请求开启 await $api('/users', { toast: { success: { show: true } } }) // 关闭业务状态码检查(仍按 dataKey 解包) const data = await $api('/external-api/data', { businessCheck: false }) ``` 用户传入的 `onRequest` / `onResponse` 等钩子与内置拦截器组合执行(内置在前),不会覆盖认证、业务校验、解包与 Toast: ```ts await $api('/users', { onResponse({ response }) { // response._data 已按策略解包 } }) ``` > [!NOTE] > > 这些选项经 ofetch 的 > > FetchOptions > > 类型扩展声明,仅 Movk Nuxt 的 > > $api > > 客户端识别;原生 > > $fetch > > 会忽略它们。 ## 错误处理 `$api` 抛出的所有错误都是 `ApiError`(`NuxtError`),按 `error.data.kind` 区分 `business`、`http`、`network`、`timeout`、`aborted`。错误 Toast 与 `movk:api:error` 在 ofetch 重试结束后只触发一次,主动中止不上报: ```ts try { await $api('/orders', { method: 'POST', body }) } catch (error) { const { kind, code } = (error as ApiError).data ?? {} if (kind === 'business' && code === 40001) { // 业务码分支 } } ``` ## API ### ApiInstance `$api` 的类型定义: ```ts type ApiInstance = $Fetch & { use: (endpoint: string) => ApiInstance stream: (url: string, options?: ApiStreamOptions) => Promise> } ``` **$api(url, options)** (`Promise`): 发送 API 请求。支持所有 ofetch 选项,额外支持 ApiRequestOptions 中的字段。$api.raw 返回完整响应,走同一条管线。 **$api.use(endpoint)** (`ApiInstance`): 切换到指定端点,返回该端点的 $api 实例。endpoint 类型为 MovkApiEndpointName(由模块按 movk.api.endpoints 声明合并出的字面量联合)。端点实例内部有缓存,多次调用返回同一实例。 ### ApiRequestOptions 与 ofetch 选项同层传入的请求级配置: **toast** (`RequestToastOptions | false`): Toast 提示配置。设为 false 禁用所有 Toast;{ success: { show: true } } 可覆盖全局关闭单次开启。 **businessCheck** (`boolean`): 是否按 successCodes 校验业务状态码。未传时继承端点 / 全局 response.businessCheck;设为 false 时不抛业务 ApiError,但仍按 dataKey 解包。 **unwrap** (`boolean`): 是否按 dataKey 解包。未传时继承端点 / 全局 response.unwrap;设为 false 时拦截器不重写 response._data,调用方拿到原始响应体。与 businessCheck 正交。 ### ApiError ```ts type ApiError = NuxtError interface ApiErrorData { kind: 'business' | 'http' | 'network' | 'timeout' | 'aborted' endpoint: string code?: number | string response?: unknown } ``` **statusCode** (`number`): HTTP 失败时为状态码;业务失败时业务码落在 100–599 内取业务码,否则为 500。 **message** (`string`): 错误文案,优先取响应体中 messageKey 字段。 **data.kind** (`ApiErrorKind`): 错误分类:business 业务码校验失败、http HTTP 4xx/5xx、network 未拿到响应、timeout 超时、aborted 主动中止。 **data.code** (`number | string`): 原始业务码(business)或 HTTP 状态码(http)。 **data.response** (`unknown`): 原始响应体。 # hooks > 通过 Nuxt 运行时 Hook 扩展 API 系统行为,实现全局请求拦截、错误处理和 401 自定义处理。 ## 介绍 Movk Nuxt API 系统通过 Nuxt 运行时 Hook 暴露 4 个扩展点,可以在不修改源码的情况下扩展/定制 API 行为。 所有 Hook 类型已通过模块声明自动注册到 `RuntimeNuxtHooks`,编辑器中 `nuxtApp.hook('movk:api:')` 可获得完整自动补全。 ## 可用 Hooks ### `movk:api:request` **触发时机**: 认证 token 注入完成后,请求实际发送前。 ```ts 'movk:api:request': (context: FetchContext) => void | Promise ``` 典型用途:添加额外请求头、请求日志、修改请求参数。 ```ts [plugins/api-logger.ts] export default defineNuxtPlugin((nuxtApp) => { nuxtApp.hook('movk:api:request', (context) => { console.log(`[API] ${context.options.method || 'GET'} ${context.request}`) }) }) ``` ### `movk:api:response` **触发时机**: 业务状态码校验通过 + 数据解包完成后。 ```ts 'movk:api:response': ( context: FetchContext & { response: FetchResponse } ) => void | Promise ``` 此时 `context.response._data` 已经是解包后的业务数据。 典型用途:全局数据转换、响应日志、性能分析。 ```ts [plugins/api-analytics.ts] export default defineNuxtPlugin((nuxtApp) => { nuxtApp.hook('movk:api:response', (context) => { analytics.track('api_success', { url: context.request, method: context.options.method || 'GET' }) }) }) ``` ### `movk:api:error` **触发时机**: 业务状态码校验失败、HTTP 错误(4xx/5xx)、网络中断或超时。在 ofetch 重试结束后**只触发一次**;主动中止不触发。对于 401 错误,在 `movk:api:unauthorized` 之后触发,被业务侧接管时跳过。 ```ts 'movk:api:error': ( context: FetchContext, error: ApiError ) => void | Promise ``` `error` 是归一后的 [`ApiError`](https://nuxt.mhaibaraai.me/docs/api/api-plugin#apierror),`error.data` 携带分类、端点、业务码与原始响应体。典型用途:全局错误上报(Sentry 等)、错误分析。 ```ts [plugins/error-reporter.ts] export default defineNuxtPlugin((nuxtApp) => { nuxtApp.hook('movk:api:error', (context, error) => { if (error.data?.kind === 'network') return Sentry.captureException(error, { extra: { url: context.request, endpoint: error.data?.endpoint, response: error.data?.response } }) }) }) ``` ### `movk:api:unauthorized` **触发时机**: 收到 HTTP 401 响应,或响应体业务码(`codeKey`,兼容字符串)为 401 时,在 `movk:api:error` **之前**触发。上传 / 下载进度请求同样适用。 ```ts 'movk:api:unauthorized': ( context: FetchContext, result: { handled: boolean } ) => void | Promise ``` 设置 `result.handled = true` 可**跳过默认的 401 处理**(清除 session + 跳转登录页),同时跳过后续的 `movk:api:error` 与错误 Toast(当前失败请求本身仍会抛出 `ApiError`)。 > [!WARNING] > > 如果多个处理器监听此 Hook,任一处理器设置 > > result.handled = true > > 即可阻止默认行为。 #### Token 刷新模式 ```ts [app/plugins/token-refresh.ts] export default defineNuxtPlugin((nuxtApp) => { let refreshing: Promise | null = null nuxtApp.hook('movk:api:unauthorized', async (_context, result) => { // 刷新 Cookie 会话仅在浏览器端执行 if (import.meta.server) return try { // 并发 401 共享同一个刷新 Promise,避免重复请求或漏设 handled refreshing ??= $fetch('/api/auth/refresh', { method: 'POST' }) .then(() => useUserSession().fetch()) .finally(() => { refreshing = null }) await refreshing result.handled = true // 重新拉取当前页面活跃的 useApiFetch / useAsyncData 查询 await refreshNuxtData() } catch { // 刷新失败不设 handled,交由默认流程清 session 并跳转登录页 } }) }) ``` ## 注册方式 ### 在 Nuxt 插件中(推荐) 适合全局逻辑,应用启动时自动注册: ```ts [plugins/api-hooks.ts] export default defineNuxtPlugin((nuxtApp) => { nuxtApp.hook('movk:api:request', (context) => { // 全局请求处理 }) nuxtApp.hook('movk:api:error', (context, error) => { // 全局错误处理 }) }) ``` ### 在组件中 适合特定页面的局部逻辑: ```vue ``` > [!NOTE] > > 在组件中注册 Hook 时,务必通过 > > onUnmounted > > 调用返回的卸载函数以避免内存泄漏。 ## 执行顺序 ```text 请求发起 │ ├── 认证 token 注入 ├── Debug 日志 ├── movk:api:request <-- 用户扩展点 │ ├── 网络请求发送 ─────────────> │ ├── HTTP 2xx 响应 │ ├── 业务成功 (code in successCodes,或已关闭 businessCheck) │ │ ├── 数据解包 (提取 dataKey,已关闭 unwrap 时跳过) │ │ ├── movk:api:response <-- 用户扩展点 │ │ └── 成功 Toast │ │ │ └── 业务失败 → 抛 ApiError(kind: business),进入出口 │ ├── HTTP 4xx/5xx → ofetch 按 retry 重试,仍失败则进入出口 ├── 网络中断 / 超时 → 进入出口 │ └── 出口(每次请求只执行一次,主动中止跳过) ├── 归一为 ApiError ├── [HTTP 或业务码 401] movk:api:unauthorized <-- 用户扩展点 │ └── (未 handled) 清 session + 跳转登录 ├── movk:api:error <-- 用户扩展点(已 handled 的 401 跳过) ├── 错误 Toast <-- 已 handled 的 401 跳过 └── throw ApiError ``` ## TypeScript 支持 Hook 类型已通过模块声明自动注册: ```ts [src/runtime/types/module.ts] declare module 'nuxt/app' { interface RuntimeNuxtHooks { 'movk:api:request': (context: FetchContext) => void | Promise 'movk:api:response': (context: FetchContext & { response: FetchResponse }) => void | Promise 'movk:api:error': (context: FetchContext, error: ApiError) => void | Promise 'movk:api:unauthorized': ( context: FetchContext, result: { handled: boolean } ) => void | Promise } } ``` 无需额外配置,`nuxtApp.hook('movk:api:...')` 即可获得完整的类型推断和自动补全。 # useApiFetch > 基于 Nuxt useFetch 封装的 API 请求 composable,提供自动认证、业务状态码检查和 Toast 提示。 ## 用法 使用自动导入的 `useApiFetch` composable 进行 API 请求,基于 Nuxt [`useFetch`](https://nuxt.com/docs/api/composables/use-fetch) 封装,提供自动认证、数据解包、业务状态码检查和统一的错误处理。 ```vue ``` - `useApiFetch` 继承 Nuxt [`useFetch`](https://nuxt.com/docs/api/composables/use-fetch) 的所有功能,同时提供额外的 API 集成特性。 - 自动从 session 获取 token 并添加到请求头(通过 `$api` 实例)。 - 自动检查业务状态码并抛出错误。 - 内置 Toast 提示,支持自定义配置。 ## 数据请求模式 Movk Nuxt 提供三种数据请求 composable,签名一致,按执行时机选择: | Composable | 执行时机 | 阻塞导航 | 场景 | | --- | --- | --- | --- | | [`useApiFetch`](https://nuxt.mhaibaraai.me/docs/api/use-api-fetch) | SSR + CSR | 是 | 首屏核心数据 | | [`useLazyApiFetch`](https://nuxt.mhaibaraai.me/docs/api/use-api-fetch#uselazyapifetch) | SSR + CSR | 否 | 次要 / 非首屏数据 | | [`useClientApiFetch`](https://nuxt.mhaibaraai.me/docs/api/use-api-fetch#useclientapifetch) | 仅 CSR | 否 | 非 SEO 敏感数据 | `useApiFetch` 在 SSR 阶段就发起请求,首屏直出数据: ```vue [ApiQuickstartSsrExample.vue] ``` ## 数据解包与转换 `useApiFetch` 接收到的已是 [`$api`](https://nuxt.mhaibaraai.me/docs/api/api-plugin#%E6%95%B0%E6%8D%AE%E8%A7%A3%E5%8C%85%E4%B8%8E%E4%B8%9A%E5%8A%A1%E6%A0%A1%E9%AA%8C) 解包后的业务数据,泛型 `T` 直接声明该数据类型;`transform` 接收解包后的数据做二次转换: ```ts // 泛型 T 直接声明业务数据类型(即 data 字段的类型) const { data } = await useApiFetch('/user') // data.value = { id: 1, name: 'test' } // 结合 transform 做二次转换 const { data } = await useApiFetch<{ content: User[] }, SelectItem[]>('/users', { transform: ({ content }) => content.map(u => ({ label: u.name, value: u.id })) }) ``` > [!TIP] > See: /docs/api/api-plugin#数据解包与业务校验 > > 解包机制、 > > unwrap > > / > > businessCheck > > 的交互示例见 > > $api > > 页 ## 业务状态码检查 `$api` 拦截器自动检查业务状态码,不在 `successCodes` 中时抛出 `ApiError`(见下方[错误分类](#%E9%94%99%E8%AF%AF%E5%88%86%E7%B1%BB))。传 `businessCheck: false` 关闭校验,但仍解包 `dataKey` 字段: ```ts const { data } = await useApiFetch('/external', { businessCheck: false }) ``` 整个端点都不返回信封时,在端点 `response` 上声明,免去逐请求传参: ```ts const { data } = await useApiFetch('/point-numbers', { endpoint: 'sensor' }) ``` > [!TIP] > See: /docs/api/api-plugin#端点级声明 > > 端点级声明与优先级见 > > $api > > 页 ## 错误分类 所有失败统一为 [`ApiError`](https://nuxt.mhaibaraai.me/docs/api/api-plugin#apierror)(`NuxtError`),经 `useAsyncData` 时原样保留;按 `error.value.data.kind` 区分场景。下拉切换错误类型观察 `error.value` 形态: - `business`:HTTP 200 但 `code` 不在 `successCodes` 内,`data.code` 保留原始业务码。 - `http-400` / `http-500`:`kind` 为 `http`,`statusCode` 为对应码;GET 的 5xx 会按 ofetch 默认重试一次,错误只上报一次。 - `http-422`:`data.response` 携带服务端补充信息。 - `network`:连接被强制断开,请求拿不到响应。 - `timeout`:超出 `timeout` 设定的毫秒数。 ```vue [ApiErrorsExample.vue] ``` ## Toast 提示 `toast` 选项支持请求级配置:`false` 全关、`{ success: false }` 仅留错误、`successMessage` / `errorMessage` 快捷文本,或传完整 [`Toast`](https://ui.nuxt.com/components/toast) 属性(`color`、`icon`、`duration` 等): ```ts // 关闭 Toast / 仅保留错误提示 / 快捷文本 await useApiFetch('/users', { toast: false }) await useApiFetch('/users', { toast: { success: false } }) await useApiFetch('/users', { toast: { successMessage: '创建成功!', errorMessage: '创建失败,请重试' } }) // 完整 Toast 属性 await useApiFetch('/users', { toast: { success: { title: '创建成功', color: 'success', icon: 'i-lucide-circle-check' }, error: { title: '创建失败', color: 'error', duration: 5000 } } }) // 全局关闭成功提示时,单次请求用 show: true 开启 await useApiFetch('/users', { toast: { success: { show: true } } }) // 自定义文案同样是开启意图:全局关闭或方法未命中白名单时也会弹出 await useApiFetch('/users', { toast: { successMessage: '创建成功!' } }) ``` > [!NOTE] > > 开关优先级:请求级 > > show > > 显式声明 > 请求级 > > successMessage > > / > > errorMessage > > > 全局 > > success.show > > / > > error.show > > / > > methods > > > 全局 > > enabled > > 。全局配置为 > > toast.success.show: false > > 时,请求级传 > > { success: { show: true } } > > 或 > > { successMessage: '...' } > > 都会弹出;要明确静默请传 > > { success: false } > > 或 > > { success: { show: false } } > > 。 > [!TIP] > See: /docs/getting-started/configuration#toast-选项 > > 只想为 POST / PUT / PATCH / DELETE 弹成功提示,请在全局或端点配置 > > toast.success.methods > > ;该字段不接受请求级传入 > [!TIP] > See: /docs/api/api-plugin#toast-提示 > > 五种 Toast 模式的交互示例见 > > $api > > 页 ## API ### useApiFetch() `useApiFetch(url: string | (() => string), options?: UseApiFetchOptions): UseApiFetchReturn`{lang="ts-type"} 创建 API 请求。 #### Parameters **url** (`string | (() => string)`) *required*: 请求 URL 或返回 URL 的函数。支持响应式 URL。 **options** (`UseApiFetchOptions`): 请求配置选项。支持所有 Nuxt useFetch 选项,以及额外的 API 集成选项。API 集成选项使用指定的端点配置。默认使用 $api 的默认端点。Toast 提示配置。设为 false 禁用 Toast。成功提示配置。可以是完整的 Toast 属性对象,或 false 禁用成功提示;show: true 可覆盖全局关闭。错误提示配置。可以是完整的 Toast 属性对象,或 false 禁用错误提示;show: true 可覆盖全局关闭。成功提示的快捷文本。等价于 success: { title: '...' }。错误提示的快捷文本。等价于 error: { title: '...' }。是否校验业务状态码。未传时继承端点 / 全局 response.businessCheck;为 false 时不抛业务 ApiError,但仍解包 dataKey 字段。是否按 dataKey 解包。未传时继承端点 / 全局 response.unwrap;为 false 时返回原始响应体。与 businessCheck 正交。请求选项 (继承自 useFetch)HTTP 请求方法。默认 'GET'。URL 查询参数,会自动序列化到 URL。query 的别名。请求体。对于 POST/PUT/PATCH 请求,会自动序列化为 JSON。请求头。基础 URL。通常通过 endpoint 选项配置,无需手动设置。响应处理转换响应数据的函数。接收已解包的业务数据,返回最终数据。仅选择响应数据的指定字段。设置默认值的工厂函数。执行选项是否立即执行请求。设为 false 时需手动调用 execute()。默认 true。是否使用 lazy 模式。lazy 模式下不会阻塞客户端导航,数据在后台加载。默认 false。是否在服务端执行请求。默认 true。监听的响应式源,变化时自动重新请求。可以是 ref、reactive 对象或数组。是否深度监听 watch 的对象。默认 true。缓存与去重自定义缓存键。用于多个请求之间共享数据或去重。重复请求的处理策略。默认 cancel'cancel' - 取消待处理的请求'defer' - 不发起新请求从缓存中获取数据的函数。返回值将用作初始 data。请求钩子请求发送前的钩子。与内置钩子合并执行。onRequest({ request, options }) { console.log('发送请求:', request.url) } 请求错误时的钩子。与内置钩子合并执行。onRequestError({ request, error }) { console.error('请求错误:', error) } 收到响应时的钩子。内置钩子先执行,因此 response._data 已是解包后的业务数据(除非 unwrap 为 false),且仅业务成功时触发。返回值被 ofetch 忽略,仅用于副作用;变形输出请用 transform。onResponse({ response }) { console.log('已解包数据:', response._data) } 响应错误时的钩子(4xx/5xx)。原样交给 ofetch,重试时每次失败都会触发;统一的错误处理请用 movk:api:error hook。onResponseError({ response }) { console.error('响应错误:', response.status) } #### Type Parameters **T** (`type`): 业务数据类型(已由 $api 自动解包)。即 API 响应中 data 字段的数据类型。 **DataT** (`type`): transform 转换后的最终类型。默认等于 T。 #### Returns 返回 [`useFetch`](https://nuxt.com/docs/api/composables/use-fetch#return-values) 的响应对象,包含以下属性: **data** (`Ref`): 响应数据(已解包和转换)。初始值为 null,请求成功后更新为实际数据。 **error** (`Ref`): 错误对象。所有失败统一为 ApiError,按 data.kind 区分业务、HTTP、网络与超时错误。 **status** (`Ref<'idle' | 'pending' | 'success' | 'error'>`): 请求状态。'idle' - 尚未开始(仅 immediate: false 时)'pending' - 请求进行中'success' - 请求成功'error' - 请求失败 **pending** (`Ref`): 是否正在请求中。等价于 status.value === 'pending'。 **refresh** (`(opts?: { dedupe?: boolean }) => Promise`): 刷新数据,重新执行请求。别名: execute。// 刷新数据 await refresh() // 跳过去重检查,强制刷新 await refresh({ dedupe: false }) **execute** (`(opts?: { dedupe?: boolean }) => Promise`): refresh 的别名。手动执行请求(常用于 immediate: false 时)。 **clear** (`() => void`): 清空状态。将 data 设为 null、error 设为 null、status 设为 'idle'。 ## Changelog See commit history for [src/runtime/composables/useApiFetch.ts](https://github.com/mhaibaraai/movk-nuxt/commits/main/src/runtime/composables/useApiFetch.ts). ## useLazyApiFetch ### 用法 使用自动导入的 `useLazyApiFetch` composable 进行 API 请求,等价于 `useApiFetch(url, { ...options, lazy: true })`。lazy 模式下请求不会阻塞客户端导航,页面立即显示,数据在后台加载。 ```vue ``` - `useLazyApiFetch` 不会阻塞客户端导航,适合非关键数据(如用户列表、评论等)。 - 客户端导航时 `data` 初始为 `null`,`status` 为 `'pending'`,需要处理加载状态。 - 继承 `useApiFetch` 的所有功能(认证、Toast、业务状态码检查等)。 > [!NOTE] > > 对于首屏必需的数据,应使用 > > useApiFetch > > (非 lazy 模式),以阻塞导航确保数据就绪。 > [!TIP] > See: /docs/api/use-api-fetch > > 完整的 API 选项和功能说明请参考 > > useApiFetch > > 文档 ### 示例 页面先渲染、随后进入 pending,`data` 在拿到响应前为 `null`,需配合 `pending` / `status` 处理加载态: ```vue [ApiQuickstartLazyExample.vue] ``` ### API #### useLazyApiFetch() `useLazyApiFetch(url: string | (() => string), options?: UseApiFetchOptions): UseApiFetchReturn`{lang="ts-type"} 创建懒加载的 API 请求。 ##### Parameters **url** (`string | (() => string)`) *required*: 请求 URL 或返回 URL 的函数。支持响应式 URL。 **options** (`UseApiFetchOptions`): 请求配置选项。支持所有 useApiFetch 的选项。[!NOTE]lazy 选项会被强制设为 true,无需手动指定。 ##### Type Parameters **T** (`type`): 业务数据类型(已由 $api 自动解包)。 **DataT** (`type`): transform 转换后的最终类型。默认等于 T。 ##### Returns 返回值与 [`useApiFetch`](https://nuxt.mhaibaraai.me/docs/api/use-api-fetch#returns) 相同。 ### Changelog See commit history for [src/runtime/composables/useApiFetch.ts](https://github.com/mhaibaraai/movk-nuxt/commits/main/src/runtime/composables/useApiFetch.ts). ## useClientApiFetch ### 用法 使用自动导入的 `useClientApiFetch` composable 进行仅客户端的 API 请求。等价于 `useApiFetch(url, { ...options, server: false, lazy: true })`。 ```vue ``` - `useClientApiFetch` 继承 [`useApiFetch`](https://nuxt.mhaibaraai.me/docs/api/use-api-fetch) 的所有功能(认证、Toast、业务状态码检查等)。 - 预设 `server: false` + `lazy: true`,请求不阻塞导航且仅在客户端执行。 - 默认 hydration 后自动发起请求。如需手动控制,额外传入 `immediate: false`。 > [!WARNING] > > 由于 > > server: false > > 的特性,SSR 阶段没有数据。初始渲染时 > > data > > 为 > > null > > ,需使用 > > pending > > 或 > > status > > 管理加载状态。 ### 示例 跳过 SSR,仅在浏览器 hydration 后发起请求;SSR 阶段无数据,初始 `data` 为 `null`: ```vue [ApiQuickstartClientExample.vue] ``` ### API #### useClientApiFetch() `useClientApiFetch(url: string | (() => string), options?: UseApiFetchOptions): UseApiFetchReturn`{lang="ts-type"} 创建仅客户端执行的 API 请求。 ##### Parameters **url** (`string | (() => string)`) *required*: 请求 URL 或返回 URL 的函数。 **options** (`UseApiFetchOptions`): 请求配置选项。完整选项参考 useApiFetch。以下选项会被强制设置,无法通过 options 覆盖:server: false - 禁用服务端执行lazy: true - 启用 lazy 模式(不阻塞导航) ##### Type Parameters 参数与 [`useApiFetch`](https://nuxt.mhaibaraai.me/docs/api/use-api-fetch#type-parameters) 相同。 ##### Returns 返回值与 [`useApiFetch`](https://nuxt.mhaibaraai.me/docs/api/use-api-fetch#returns) 相同。 ### Changelog See commit history for [src/runtime/composables/useApiFetch.ts](https://github.com/mhaibaraai/movk-nuxt/commits/main/src/runtime/composables/useApiFetch.ts). # 上传与下载 > 带进度监控的文件上传与下载。 ## useUploadWithProgress ### 用法 `useUploadWithProgress` 以 XHR 适配器作为底层 fetch 接入 `$api` 同一条管线(fetch 规范在主流浏览器上仍无法报告上传进度),端点请求头、认证、业务校验、Toast、错误归一与 `movk:api:*` hook 与 `useApiFetch` 完全一致。返回的 `data` 按端点策略解包,失败统一为 `ApiError`。 ```vue ``` > [!NOTE] > > 适用于需要展示上传进度的场景。对于无需进度的小文件,可以直接使用 > > $api > > 发起请求。 ### 基础多文件上传 `fieldName` 决定 FormData 字段名(默认 `'file'`);`upload()` 返回 `{ data, error, aborted }`: ```vue [ComposablesUseUploadProgressBasicExample.vue] ``` ### 单文件、多文件与额外字段 `files` 传 `File` 为单文件、传 `File[]` 为多文件(同 `fieldName` 追加);`fields` 注入额外表单字段一并提交: ```ts await upload('/api/upload', file, { fieldName: 'file' }) await upload('/api/upload', [f1, f2, f3], { fieldName: 'files' }) await upload('/api/upload', file, { fieldName: 'avatar', fields: { userId: '123', visibility: 'private' } }) ``` ```vue [ComposablesUseUploadProgressSingleExample.vue] ``` ### 超时 `timeout` 设定上传超时毫秒数(0 或省略不超时),超时后以 `TimeoutError` 中止,`error.data.kind` 为 `timeout`: ```vue [ComposablesUseUploadProgressTimeoutExample.vue] ``` ### 跨域携带凭证 ```ts await upload('https://other.example/upload', file, { withCredentials: true }) ``` ### 取消上传 ```ts const { status, upload, abort } = useUploadWithProgress() upload('/api/upload', largeFile) function handleCancel() { if (status.value === 'pending') abort() } ``` 取消后: - `status` 变为 `'aborted'`,`progress` 重置为 `0` - `error` 保持 `null`(不视为失败) - 不触发 `onSuccess` / `onError`,不弹 Toast - `upload()` 返回 `{ data: null, error: null, aborted: true }` ### 认证 自动从 session 读取 token 注入到 `Authorization` 头;可在 `headers` 中覆盖同名头(用户优先)。 ```ts await upload('/api/upload', file, { headers: { Authorization: 'Bearer override' } }) ``` ### API #### useUploadWithProgress() `useUploadWithProgress(): { progress, status, data, error, upload, abort }`{lang="ts-type"} ##### Returns **progress** (`Ref`): 上传进度,0-100;类型与下载侧对齐保留 null 形态,上传场景实际不会出现。 **status** (`Ref`): 传输状态:'idle' | 'pending' | 'success' | 'error' | 'aborted'。 **data** (`Ref`): 按 dataKey 解包后的业务数据。 **error** (`Ref`): 错误对象;业务错误为 ApiError,HTTP/网络错误为 Error。中止时为 null。 **upload()** (`(url: string, files: File | File[], options?: UploadWithProgressOptions) => Promise>`): 执行上传。Parameters默认 'file'。与端点请求头合并;启用认证时 auth 头最后注入、优先级最高,与 $api 一致。是否校验业务状态码,未传时继承端点配置;为 false 时仍按 dataKey 解包。是否按 dataKey 解包,未传时继承端点配置。超时毫秒数,0 或省略不超时。解包后的业务数据。ReturnsPromise>:{ data: T | null, error: ApiError | null, aborted: boolean }。 **abort()** (`() => void`): 中止当前上传,status 切到 'aborted'。 ### Changelog See commit history for [src/runtime/composables/上传与下载.ts](https://github.com/mhaibaraai/movk-nuxt/commits/main/src/runtime/composables/上传与下载.ts). ## useDownloadWithProgress ### 用法 `useDownloadWithProgress` 基于 `$api.raw` 以流式响应读取并汇报进度,端点请求头、认证、业务校验、Toast、错误归一与 `movk:api:*` hook 与 `useApiFetch` 完全一致;请求体由 ofetch 序列化,失败统一为 `ApiError`。 后端返回 `application/json` 时走业务校验,**不会**把错误响应当作二进制写入文件;返回二进制时按 `content-length` 计算进度,缺失时 `progress` 为 `null`,UI 据此切 indeterminate。 ```vue ``` > [!NOTE] > > 适用于大文件导出、批量下载等场景。对于无需进度的小文件,直接使用 > > $api > > 即可。 ### 基础下载 `content-length` 已知时进度按比例更新,`abort()` 中止流式读取: ```vue [ComposablesUseDownloadProgressBasicExample.vue] ``` ### 文件名提取 优先级: 1. `options.filename` 2. 响应头 `Content-Disposition`(支持 RFC 5987 编码) 3. URL pathname 末段(自动去除 query string) 4. `'download'` ```ts await download('/api/export?token=abc') // 自动取得 export 作为 fallback 文件名,query 不会污染 ``` ### 不确定进度 当响应缺少 `content-length`(如分块传输),`progress` 为 `null`,通过 nullish-coalescing 映射到 `UProgress` 的 `:model-value` 即自动进入 indeterminate: ```vue [ComposablesUseDownloadProgressChunkedExample.vue] ``` ### 自定义文件名 `options.filename` 覆盖响应头与 URL 推断,强制指定下载文件名: ```vue [ComposablesUseDownloadProgressCustomExample.vue] ``` ### POST 导出 `method: 'POST'` + `body` 把筛选条件放进请求体,`Content-Type` 自动补 `application/json`: ```vue [ComposablesUseDownloadProgressPostExample.vue] ``` ### 取消下载 ```ts const { status, download, abort } = useDownloadWithProgress() download('/api/export/large.zip') function handleCancel() { if (status.value === 'pending') abort() } ``` 取消后: - `status` 变为 `'aborted'`,`progress` 重置为 `0` - `error` 保持 `null`(不视为失败) - 不触发 `onError`,不弹 Toast - `download()` 返回 `{ data: null, error: null, aborted: true }` ### 认证 自动从 session 读取 token 注入到 `Authorization` 头;可在 `headers` 中覆盖(用户优先)。 ```ts await download('/api/export/private.pdf', { headers: { 'X-Custom': 'value' } }) ``` ### API #### useDownloadWithProgress() `useDownloadWithProgress(): { progress, status, data, error, download, abort }`{lang="ts-type"} ##### Returns **progress** (`Ref`): 下载进度,0-100;缺 content-length 时为 null,UI 据此切 indeterminate。 **status** (`Ref`): 传输状态:'idle' | 'pending' | 'success' | 'error' | 'aborted'。 **data** (`Ref`): 二进制路径下为 Blob;JSON 路径下为解包后的业务数据。 **error** (`Ref`): 错误对象;业务错误为 ApiError,HTTP/网络错误为 Error。中止时为 null。 **download()** (`(url: string, options?: DownloadWithProgressOptions) => Promise>`): 执行下载。Parameters默认 'GET'。非 GET 时序列化为 JSON。与端点请求头合并;启用认证时 auth 头最后注入、优先级最高,与 $api 一致。是否校验业务状态码,未传时继承端点配置;为 false 时仍按 dataKey 解包。是否按 dataKey 解包,未传时继承端点配置。ReturnsPromise>:{ data: T | null, error: ApiError | null, aborted: boolean }。 **abort()** (`() => void`): 中止当前下载,status 切到 'aborted'。 ### Changelog See commit history for [src/runtime/composables/上传与下载.ts](https://github.com/mhaibaraai/movk-nuxt/commits/main/src/runtime/composables/上传与下载.ts). # 流式请求 > SSE 流式请求与 AI SDK Chat Transport。 ## useApiStream ### 用法 `useApiStream` 是 [`$api.stream()`](#apistream) 的响应式外壳,返回一个惰性异步生成器,开始迭代才真正发起请求。SSE 的行缓冲、`data:` 多行拼接、注释行与 `\r\n` 全部交给 `eventsource-parser`,解析不了的事件静默跳过——一条心跳或握手行不该中断整条流。 ```vue ``` 重新发起会自动中止上一条流,组件作用域销毁时同样中止。 ### Accept 与 responseType 的处理 > [!WARNING] > > 这两处的默认值都是踩过坑定下来的,改动前请先确认自家网关的行为。 **Accept 默认发通配符,既不是 `application/json` 也不是 `text/event-stream`**。ofetch 见到可 JSON 序列化的 body 会自动塞 `Accept: application/json`——对一条要当流读的请求,这个声明本身就是错的,按 Accept 做内容协商的后端可能据此改走 JSON 渲染器;而主动发 `Accept: text/event-stream` 又会被这类后端(如 DRF)直接拒掉整个请求,实测返回「无法满足 Accept HTTP 头的请求」,连业务逻辑都不进。通配符两头都不踩。需要指定的网关自行传,调用方传了就以调用方为准: ```ts stream('/chat', { headers: { Accept: 'text/event-stream' } }) ``` **默认 `responseType: 'stream'`**:网关把事件流标成非 `text/event-stream` 类型也照常按流读取。`application/json` 响应(含 HTTP 200 + `{ code: 500 }` 这类错误信封)由拦截器先还原为对象,再走业务码校验抛出后端文案,不会变成一条读不出东西的流。 响应体不是流时抛出可读错误,不会静默空转。 ### 错误与中止 - 主动中止(`abort()`、重新发起、作用域销毁)不计入错误态:`status` 置 `'aborted'`,`error` 保持 `null`,迭代静默结束 - 其余错误:写入 `error`、`status` 置 `'error'`、调用 `onError`,然后**继续抛出**,`for await` 外层的 `try/catch` 能接住 - 业务错误(`code` 不在 `successCodes`)在流开始前就由拦截器抛出,toast 与 `movk:api:error` hook 一并走通 ```ts try { for await (const chunk of stream('/chat', { onError: e => console.error(e) })) { // ... } } catch (error) { // 业务错误、HTTP 错误、流中断 } ``` ### $api.stream() 不在组件里、或不需要响应式状态时,直接用 `$api.stream()`: ```ts const { $api } = useNuxtApp() for await (const chunk of await $api.stream('/chat', { method: 'POST', body })) { console.log(chunk.content) } ``` 响应是流时,响应拦截器整段短路——不解包、不校验业务码、不弹成功 toast,`_data` 原样保留,调用方无需再传 `unwrap` / `businessCheck`。 接 AI SDK 与 `@nuxt/ui` 的 Chat 组件请改用 [`createChatTransport`](https://nuxt.mhaibaraai.me/docs/api/stream)。 ### API #### useApiStream() ##### Type Parameters **T** (`unknown`): 单条分片的类型。 ##### Returns **status** (`Ref`): 'idle' | 'streaming' | 'success' | 'error' | 'aborted'。开始迭代前为 'idle'。 **error** (`Ref`): 错误信息,主动中止不写入。 **stream()** (`(url: string, options?: UseApiStreamOptions) => AsyncGenerator`): 发起流式请求,逐条产出分片。Parameters使用的端点名称,默认走 defaultEndpoint。单条 SSE 事件的 data 解析方式,返回 undefined 丢弃该条。默认容错的 JSON.parse。失败回调,主动中止不触发。其余选项原样交给 ofetch:method、body、headers、query、responseType 等。 **abort()** (`() => void`): 中止当前流,status 切到 'aborted'。 ### Changelog See commit history for [src/runtime/composables/流式请求.ts](https://github.com/mhaibaraai/movk-nuxt/commits/main/src/runtime/composables/流式请求.ts). ## createChatTransport ### 用法 `@nuxt/ui` 的 `UChat*` 组件渲染的是 AI SDK 的 `UIMessage`,协议解析全在 `ai` 包里,且只认 AI SDK 自己的 UI Message Stream 格式。内部网关(MaxKB、Dify、FastGPT、自研)的分片结构各不相同,`createChatTransport` 补的就是中间这一段:**领域侧只写一个无状态的 `select`,其余全部继承 AI SDK 的 `HttpChatTransport`。** > [!NOTE] > > 需要额外安装 > > ai > > ( > > @movk/nuxt > > 的可选 peer)与 > > @ai-sdk/vue > > ,并从 > > @movk/nuxt/ai > > 子路径导入——主包不引入 AI SDK。 ```vue ``` `createChatTransport` 内部取 `$api`,须在 setup 作用域内调用。 ### select 映射 `select` 是纯函数:拿一条后端分片,说明它对应哪些 UI 片段,返回 `undefined` 表示这条什么都不产出。生命周期由传输层兜住——`start` 只发一次、按 `id` 开合文本块、流结束时补齐所有未关闭的块与 `finish`,因此后端漏发结束信号或中途断流,消息也不会永远停在 streaming。 **id** (`string`): 文本块 id,同 id 的增量并入同一块。省略则并入默认块 'text-1'。 **delta** (`string`): 本片增量文本,为空则不产出 text-delta。 **end** (`boolean`): 该文本块到此结束。 **data** (`{ type: string, value: unknown, transient?: boolean }`): 附带的自定义数据片,产出 data-${type}。transient: true 时只走 useChat 的 onData 回调、不写入消息历史。 **finished** (`boolean`): 整条流到此结束,其后的分片被忽略。 工作流类网关常在正文之外带节点信息,用 `data` 片把它送到 `onData`,就能在不污染消息历史的前提下驱动进度: ```ts const transport = createChatTransport({ api: '/chat/completions', select: raw => ({ id: raw.runtime_node_id, delta: raw.content, end: raw.node_is_end, finished: raw.is_end, data: { type: 'node', value: { nodeId: raw.node_id, nodeIsEnd: raw.node_is_end }, transient: true } }) }) const { messages } = useChat({ transport, onData: (part) => { if (part.type === 'data-node') advanceStage(part.data) } }) ``` ### 请求编排 `api`、`headers`、`body`、`credentials`、`prepareSendMessagesRequest`、`prepareReconnectToStreamRequest` 全部是 AI SDK `HttpChatTransport` 的原生选项,行为一致。私有握手(先开会话再拼流地址)放在 `prepareSendMessagesRequest` 里即可,它允许异步、允许覆盖 `api`: ```ts const transport = createChatTransport({ prepareSendMessagesRequest: async ({ messages }) => { const chatId = await $api('/chat/open') return { api: `/chat_message/${chatId}`, body: { message: getTextFromMessage(messages.at(-1)!) } } }, select }) ``` ### 为什么默认 fetch 走 $api 默认注入的 `fetch` 基于 `$api`,端点 baseURL、鉴权头、业务码校验、错误 toast 与 `movk:api:*` hook 全部复用。这不只是省事:**有些网关的错误响应是 HTTP 200 + `{ code: 500 }` 信封**,只看 `response.ok` 的实现会放行,然后拿 JSON 当流读、静默空转。走 `$api` 时这类响应在业务码校验处就抛出,最终落到 `useChat` 的 `onError`。 它还顺手处理了 Accept:ofetch 见到 JSON body 会自动塞 `Accept: application/json`,对要当流读的请求是错误声明,因此默认改发通配符;调用方在 `headers` 里指定则以调用方为准。细节见 [`useApiStream`](https://nuxt.mhaibaraai.me/docs/api/stream#accept-%E4%B8%8E-responsetype-%E7%9A%84%E5%A4%84%E7%90%86)。 传入自己的 `fetch` 会覆盖该默认值,Accept 也要自己管。 ### API #### createChatTransport() ##### Type Parameters **Raw** (`unknown`): 后端单条分片的类型。 **UI_MESSAGE** (`UIMessage`): 消息类型,默认 AI SDK 的 UIMessage。 ##### Parameters **options** (`MovkChatTransportOptions`) *required*: 后端分片 → UI 片段的纯映射。使用的端点名称,默认走 defaultEndpoint。单条 SSE 事件的 data 解析方式,返回 undefined 丢弃该条。默认容错的 JSON.parse。api、headers、body、credentials、fetch、prepareSendMessagesRequest、prepareReconnectToStreamRequest,语义与 AI SDK 一致。 ##### Returns `ChatTransport`,直接传给 `useChat({ transport })`。 ### Changelog See commit history for [src/runtime/domains/ai/流式请求.ts](https://github.com/mhaibaraai/movk-nuxt/commits/main/src/runtime/domains/ai/流式请求.ts). # API 架构设计 > 厘清 @movk/nuxt 的职责边界,用最小化分层组织直连后端、同源代理与最小化 BFF,并梳理两类 Auth 的完整闭环。 在 Nuxt 项目接入 `@movk/nuxt` 后,架构变复杂通常只有两个原因:**在 `$api` / `useApiFetch` 外面重复封装拦截器**,以及**为了改字段名、透传接口或按 REST 拆文件写了大量 BFF 空壳路由与多层包装函数**。 本文直接给出可落地的边界、选型顺序、硬性分层约束与最小示例,避免项目 API 层被重重包裹。 ## 职责边界 先把 `@movk/nuxt` 已内置的能力与项目需要决策的部分划清: | 归属 | 负责什么 | 参考文档 | | --- | --- | --- | | **`@movk/nuxt` 已内置** | 多端点 `$api` 创建与缓存、服务端 `headers` 与客户端 `publicHeaders` 隔离 | [端点配置](https://nuxt.mhaibaraai.me/docs/getting-started/configuration#endpoints) · [$api](https://nuxt.mhaibaraai.me/docs/api/api-plugin) | | **`@movk/nuxt` 已内置** | 从 Session 自动注入 Token、401 自动清会话跳登录、`movk:api:unauthorized` Hook | [认证集成](https://nuxt.mhaibaraai.me/docs/api/api-plugin#%E8%AE%A4%E8%AF%81%E9%9B%86%E6%88%90) · [Hooks](https://nuxt.mhaibaraai.me/docs/api/hooks#movkapiunauthorized) | | **`@movk/nuxt` 已内置** | 业务状态码校验(`businessCheck`)、数据解包(`unwrap`)、`ApiError` 归一与 Toast 过滤 | [概览](https://nuxt.mhaibaraai.me/docs/api) · [$api](https://nuxt.mhaibaraai.me/docs/api/api-plugin) | | **`@movk/nuxt` 已内置** | SSR/CSR 缓存与去重 Key(`useApiFetch` 家族)、上传下载进度、SSE 流式解析 | [useApiFetch](https://nuxt.mhaibaraai.me/docs/api/use-api-fetch) · [上传与下载](https://nuxt.mhaibaraai.me/docs/api/upload-download) · [流式请求](https://nuxt.mhaibaraai.me/docs/api/stream) | | **你的项目负责** | 决定每类接口走直连 / 同源代理 / 最小化 BFF、管理领域契约与极薄的服务端边界 | 本文 | > [!NOTE] > > API 域依赖 Nuxt 运行时与服务端私有配置隔离, > > 仅在 Nuxt 模式下可用 > > ;纯 Vue + Vite 模式仅包含 UI 组件、AutoForm、DataTable 与通用 Composables。 ## 选型决策树 按**“直连 → 同源代理 → 最小化 BFF”**的顺序判断,同一个项目可以通过多端点混合使用: ```mermaid flowchart TD A["新增一类后端接口"] --> B{"支持 CORS 且前端可直接持凭证直连?"} B -- "是" --> C["直连后端: 仅配端点 baseURL"] B -- "否" --> D{"浏览器会话本身有权调上游,只需解决跨域、同源 Cookie 或运行时域名?"} D -- "是" --> E["同源代理: /proxy/:target/* -> 上游"] D -- "否 (需切高权限会话 / 锁租户 / 私钥 / 多步登录 / 聚合 / 分片限流 / 二进制缓存)" --> F["最小化 BFF: server/api/ -> 单一入口"] ``` | 方式 | 请求链路 | 适用场景 | | --- | --- | --- | | **直连后端** | 页面 → 后端 | 公开 API 或已配好 CORS、前端可直接携带凭证,零服务端代码 | | **同源代理** | 页面 → `/proxy/**` → 后端 | 浏览器持有的会话已有权访问上游(如直调 `/proxy/gateway/:menuId/:buttonId`),只需隐藏内网地址、消除跨域、共享同源 Cookie 或容器运行时切换后端域名 | | **最小化 BFF** | 页面 → `server/api/` → 上游 | 持有私有密钥、必须由服务端切换高权限会话并锁定租户参数、多步登录写 Session、多上游聚合、分片并发限流或二进制压缩与缓存 | > [!TIP] > > **别为了“洗字段名”或“直调网关路径”写 BFF**: > > - 上游返回 `snake_case` 或裸数组时,关闭端点的 `businessCheck` 与 `unwrap`,把 Zod `.transform()` 写在 `shared/contracts/` 里,配合 `useApiFetch` 的 `transform` 在前端一次转换即可。 > - 只要浏览器自身的会话就能调通网关接口且后端自行按会话校验租户,直接在 `app/composables/api/` 调同源代理端点,不要建 BFF。 ## 分层规则(硬约束) 保持每条调用链路清晰可追,遵守以下 6 条约束: 1. **契约只解析一次**:`shared/contracts/` 集中存放 Zod schema 与字段映射;前端直连/代理只在 Composable 或 `transform` 中解析一次,BFF 输出已映射好的页面模型,不在前后端各洗一遍。 2. **前端按领域直调**:`app/composables/api/` 按业务领域建文件,直接调用 `$api`、`useApiFetch` / `useClientApiFetch`,不自建 `request.ts` 二次包装。 3. **服务端只留单工厂与单入口**:`server/utils/` 只放一个上游客户端工厂(统一超时、日志与 `502/504` 映射)和一个同类上游的统一调用入口(如网关上下文与信封解包)。 4. **路由保持门卫职责**:`server/api/` 路由只做“参数校验 → 调用一个 Service/工具函数 → 返回统一响应信封”,避免在路由里写循环、聚合与重试。 5. **同类上游最多两层**:`路由 → 唯一调用入口 → 上游`,同类上游只允许存在一个调用入口,禁止再套“专用透传层 + 通用封装层”。 6. **消灭空壳路由与单调用方包装**:只服务于单一调用方的中转函数一律内联;必须走 BFF 的同类 CRUD/查询不要手写十几个 `[id].get/put/delete.ts` 空壳文件,收口到**读写双操作表**(`query/[op].get.ts` + `action/[op].post.ts`)。 ## 三种接入方式示例 ::code-tree{:expand-all="true" default-value="nuxt.config.ts"} ```ts [nuxt.config.ts] const baseURL = process.env.NUXT_APP_BASE_URL || '/' export default defineNuxtConfig({ modules: ['@movk/nuxt'], app: { baseURL }, // 运行时通过 NUXT_GATEWAY_URL / NUXT_SENSOR_URL / NUXT_ORDERS_TOKEN 注入 runtimeConfig: { gatewayUrl: '', sensorUrl: '', ordersToken: '' }, movk: { api: { // 仅变更类请求自动弹成功 Toast,GET 查询保持安静 toast: { success: { methods: ['POST', 'PUT', 'PATCH', 'DELETE'] } }, endpoints: { // 1. 最小化 BFF:默认启用 { code, message, data } 校验与解包 default: { baseURL: `${baseURL}api` }, // 2. 同源代理:上游多数返回裸数据,关闭默认解包,按需在单次请求开启 gateway: { baseURL: `${baseURL}proxy/gateway`, response: { businessCheck: false, unwrap: false, messageKey: 'msg' } }, // 3. 无鉴权外部/内部裸数据服务:必须显式关闭 auth,防主站 Token 外泄与误清会话 sensor: { baseURL: `${baseURL}proxy/sensor`, response: { businessCheck: false, unwrap: false }, auth: { enabled: false, unauthorized: { clearSession: false, redirect: false } } } } } } }) ``` ```ts [shared/contracts/sensor.ts] import { z } from 'zod' // 上游 snake_case 字段直接在共享契约层转换一次,不建透传 BFF const upstreamReadingSchema = z.object({ point_number: z.string(), sensor_value: z.number().nullable() }).transform(({ point_number, sensor_value }) => ({ pointNumber: point_number, value: sensor_value })) export type SensorReading = z.infer export const parseReadings = (raw: unknown): SensorReading[] => z.array(upstreamReadingSchema).parse(raw) ``` ```ts [app/composables/api/useSensor.ts] import { parseReadings, type SensorReading } from '#shared/contracts/sensor' export function useSensorLatest(point: Ref, active: Ref) { return useClientApiFetch('/readings/latest', { endpoint: 'sensor', query: { point }, enabled: computed(() => active.value && Boolean(point.value)), transform: parseReadings, toast: false }) } export async function fetchCaptcha() { const { $api } = useNuxtApp() // 同端点下个别带标准信封的接口,单次请求覆盖开启校验与解包 return await $api.use('gateway')<{ captchaId: string, img: string }>('/v1/captcha/get', { businessCheck: true, unwrap: true, toast: { success: false } }) } ``` ```ts [app/composables/api/useAdmin.ts] // 必须经 BFF 切会话/锁租户的管理操作,前端只用两个 1 行辅助函数对齐读写操作表 export function useAdminApi() { const { $api } = useNuxtApp() const query = (op: 'users' | 'roles' | 'userDetail', params?: Record) => $api(`/admin/query/${op}`, { ...(params ? { query: params } : {}) }) const act = (op: 'createUser' | 'removeUser', body: Record) => $api(`/admin/action/${op}`, { method: 'POST', body }) return { listUsers: (params: { page: number }) => query('users', params), getUserDetail: (id: string) => query('userDetail', { id }), createUser: (body: { name: string }) => act('createUser', body), removeUser: (id: string) => act('removeUser', { id }) } } ``` ```ts [server/routes/proxy/[target]/[...path].ts] export default defineEventHandler((event) => { const target = getRouterParam(event, 'target') const config = useRuntimeConfig(event) // 白名单限制可代理的上游,防止开放代理(SSRF) const upstreams: Record = { gateway: config.gatewayUrl, sensor: config.sensorUrl } const upstreamBase = target ? upstreams[target] : undefined if (!upstreamBase) { throw createError({ statusCode: 404, message: '未知代理目标' }) } const path = getRouterParam(event, 'path') || '' if (path.split('/').includes('..')) { throw createError({ statusCode: 400, message: '非法请求路径' }) } const { search } = getRequestURL(event) const base = new URL(upstreamBase.replace(/\/$/, '')) const targetUrl = `${base.origin}${base.pathname.replace(/\/$/, '')}/${path.replace(/^\//, '')}${search}` if (new URL(targetUrl).origin !== base.origin) { throw createError({ statusCode: 400, message: '非法请求路径' }) } return proxyRequest(event, targetUrl) }) ``` ```ts [server/utils/upstream.ts] import type { z } from 'zod' export function parseUpstream(schema: z.ZodType, raw: unknown, name: string): T { const result = schema.safeParse(raw) if (!result.success) { console.error(`[upstream:${name}] schema mismatch`, result.error.issues.slice(0, 5)) throw createError({ statusCode: 502, message: `${name}返回数据格式异常` }) } return result.data } export function createUpstream(name: string, baseURL: string, headers?: Record) { if (!baseURL) { throw createError({ statusCode: 500, message: `未配置 ${name} 地址` }) } return $fetch.create({ baseURL, headers, timeout: 10_000, retry: 0, onResponseError({ response }) { throw createError({ statusCode: response.status === 404 ? 404 : 502, message: `${name}异常` }) }, onRequestError({ error }) { if (error.name === 'AbortError') throw error throw createError({ statusCode: error.name === 'TimeoutError' ? 504 : 502, message: `${name}不可用` }) } }) } ``` ```ts [server/api/admin/query/[op].get.ts] import { z } from 'zod' // 读操作与详情聚合收口到 GET 操作表(GET 保持静默,不触发 POST 成功 Toast) const READS = { users: { schema: z.object({ page: z.coerce.number().default(1) }), run: (q: { page: number }) => queryAdmin('user.list', q) }, userDetail: { schema: z.object({ id: z.string().min(1) }), run: (q: { id: string }) => fetchUserDetail(q.id) } } as const const paramsSchema = z.object({ op: z.enum(['users', 'userDetail']) }) export default defineEventHandler(async (event) => { await requireUserSession(event) const { op } = await getValidatedRouterParams(event, paramsSchema.parse) const query = await getValidatedQuery(event, data => READS[op].schema.parse(data)) return { code: 200, message: 'ok', data: await READS[op].run(query) } }) ``` ```ts [server/api/admin/action/[op].post.ts] import { z } from 'zod' // 写操作统一收口到 POST 操作表(自动命中 toast.success.methods 弹出 message),告别几十个空壳文件 const ACTIONS = { createUser: { schema: z.object({ name: z.string().min(1) }), run: (b: { name: string }) => saveUser(b), message: '新增用户成功' }, removeUser: { schema: z.object({ id: z.string().min(1) }), run: (b: { id: string }) => deleteUser(b.id), message: '删除用户成功' } } as const const paramsSchema = z.object({ op: z.enum(['createUser', 'removeUser']) }) export default defineEventHandler(async (event) => { await requireUserSession(event) const { op } = await getValidatedRouterParams(event, paramsSchema.parse) const body = await readValidatedBody(event, data => ACTIONS[op].schema.parse(data)) await ACTIONS[op].run(body) return { code: 200, message: ACTIONS[op].message, data: null } }) ``` :: > [!NOTE] > > 为什么用 > > createError({ statusCode, message }) > > 而不是 > > statusMessage > > 放中文? > > HTTP 状态行的 > > statusMessage > > 只能包含 ASCII 字符,传入中文会导致 Node / Undici 直接抛 > > Invalid character in statusMessage > > 变成 500;中文提示放进 > > message > > , > > @movk/nuxt > > 会自动提取展示。 ## Auth 的两种架构 无论采用哪种方式,底层均使用 `nuxt-auth-utils` 管理加密 Cookie,**生产环境须设置至少 32 位的 `NUXT_APP_SECRET`**。 ### 情况 A:后端内置 Auth(后端签发 Token / SessionId) 适用场景:独立认证中心或网关签发 Token,前端直连或经同源代理携带自定义请求头。 1. 开启 `movk.api.auth.enabled: true`(默认从 `session.token` 读取,自动注入请求头并在 `401` 时清会话跳 `/login`;非标头如 `sessionId` 只需补 `headerName: 'sessionId', tokenType: 'Custom'`)。 2. 登录接口拿到 Token 后调 `await setUserSession(event, { user, token })`。 3. 登录页成功后依次执行 `await useUserSession().fetch()` 与 `clearNuxtData()`,再跳转页面,防止闪现旧账号缓存。 4. 如需静默续期,注册 `movk:api:unauthorized` Hook,续期成功后设 `result.handled = true` 并调 `refreshNuxtData()`。 > [!TIP] > > 若安全要求浏览器 JS 完全不可见 Token,可将 Token 存入 > > setUserSession(event, { user, secure: { token } }) > > ,关闭 > > movk.api.auth.enabled > > ,改为在同源代理 > > proxy/[target]/[...path].ts > > 中通过 > > getUserSession(event) > > 取出 > > secure.token > > 注入上游。 ### 情况 B:后端无内置 Auth(Nuxt 自己管会话,或上游只认服务密钥) 适用场景:内部算法/数据服务只认固定服务密钥,或 Nuxt 全栈自建数据库登录。 1. 显式安装并注册 `nuxt-auth-utils` 模块,保持 `movk.api.auth.enabled: false`(`auth.unauthorized` 仍可在 401 时清会话跳登录)。 2. BFF 入口调 `const { user } = await requireUserSession(event)` 鉴权,再使用 `useRuntimeConfig(event)` 中的私有密钥请求上游。 3. 在 `app/plugins/ssr-cookie.server.ts` 自动向站内同源端点转发 Cookie,解决 SSR 首屏调 `/api` 的鉴权问题(绝不向第三方外域透传): ```ts [app/plugins/ssr-cookie.server.ts] export default defineNuxtPlugin((nuxtApp) => { const { cookie } = useRequestHeaders(['cookie']) if (!cookie) return nuxtApp.hook('movk:api:request', ({ request, options }) => { const base = options.baseURL || '' const url = typeof request === 'string' ? request : '' const isSameOrigin = (base.startsWith('/') && !base.startsWith('//')) || (!base && url.startsWith('/') && !url.startsWith('//')) if (!isSameOrigin) return const headers = new Headers(options.headers as HeadersInit | undefined) if (!headers.has('cookie')) { headers.set('cookie', cookie) options.headers = headers } }) }) ``` ## 反模式清单 出现下面任意一条,说明 API 层开始过度复杂化,应立即收口: | 反模式 | 问题 | 正确做法 | | --- | --- | --- | | 为改字段名写 BFF | 平白多一层网络中转与几十个透传文件 | 关掉端点的 `unwrap`,在 `shared/contracts/` 用 Zod `.transform()` 洗一次 | | 前后端各解析一遍 | 服务端映射一遍 DTO,前端契约又 `safeParse` 一遍 | 明确唯一解析点:代理/直连在前端解析,BFF 则直接输出页面模型 | | 每个 CRUD 建一个空壳路由 | 手写十几个 `[id].get/put/delete.ts`,只做校验+转发 | 收口到读写双操作表(`query/[op].get.ts` + `action/[op].post.ts`) | | 同类上游建多个 Client 工厂 | `createClientA` / `createClientB` 散落各处,超时与错误映射不一致 | 一个 `server/utils/gateway.ts` 放统一 `createUpstream` 与单一调用入口 | | 多种响应信封并存 | BFF 混用原始网关信封与自定义 `{ code, data }`,前端被迫写两套解包逻辑 | 自建 BFF 统一返回 Movk 默认信封;原始结构只走直连或同源代理端点 | | 保留单调用方中间层 | `route → helperA → helperB → service → client` 层层转手 | 只服务一个调用方的函数直接内联,同类上游调用链路不超过两层 | | 中文塞进 `statusMessage` | Node/Undici 校验 HTTP 状态行只允许 ASCII,直接 500 崩溃 | 错误文案放进 `createError({ statusCode, message })` | ## 新增接口检查清单 每次新增后端接口前,按顺序核对以下 7 项: 1. **先判拓扑**:能直连不走代理,能同源代理不写 BFF;只有涉及私钥、高权限会话切换/锁租户、多步登录、多接口聚合、分片限流或二进制缓存才建 `server/api/`。 2. **选对端点配置**:裸数组或第三方无鉴权接口,确认端点已配置 `response: { businessCheck: false, unwrap: false }` 与 `auth: { enabled: false }`。 3. **契约落盘一处**:输入输出 schema 放 `shared/contracts/`,只在一个位置解析,不重复校验或映射。 4. **控制弹窗与并发**:`GET` 查询保持静默(全局 `toast.success.methods` 限定变更方法);同页多请求用 `useAsyncData` + `Promise.all` 并发,避免多个 `await useApiFetch` 排队。 5. **留意 `enabled` 门控时机**:`useAsyncData` / `useClientApiFetch` 的 `enabled` 仅阻断/取消,不会在 `false -> true` 时自动补发;按需抽屉面板需配合 `watch(enabled)` 在 `status === 'idle'` 时手动调用 `execute()`。 6. **守住错误边界**:上游 `ZodError` 与连接异常在服务端统一收口为 `502` / `504`(使用 `message` 传中文),绝不把上游堆栈或内部配置透出给浏览器。 7. **复用已有入口**:新增同类管理读写操作时,直接登记到既有读写操作表(`ADMIN_READS` / `ADMIN_ACTIONS`),不复制独立路由与服务模板。 # DatePicker > 基于国际化标准的日期选择器组件。 ## 简介 `MDatePicker` 是一个国际化日期选择器,基于 `@internationalized/date` 处理时区与本地化。支持单日期、日期范围、多日期选择,并提供按钮触发、可清空、快捷预设等多种交互形态。 > [!NOTE] > See: https://ui.nuxt.com/docs/components/calendar > > 基于 Nuxt UI 的 Calendar 组件封装 > [!NOTE] > See: https://react-spectrum.adobe.com/internationalized/date/index.html > > 使用 > > @internationalized/date > > 库进行日期处理,确保时区安全和国际化支持。 ## 用法 默认按钮触发器展示当前日期,点击打开日历面板后选择并写入 v-model: ```vue ``` ### `range` 日期范围 `range` 模式维护 `start` / `end` 两端日期,`numberOfMonths` 可同时展示双月日历: ```vue ``` ### `numberOfMonths` 月份数量 `numberOfMonths` 控制弹层内并排展示的月份数量,便于跨月选择: ```vue ``` ### `clearable` 可清空 `clearable` 在已有值时显示清除入口,点击后重置且不展开日历: ```vue ``` ### `presets` 快捷预设 `presets` 设为 `default` 会按当前模式自动生成「今天」「本周」「本月」等快捷项: ```vue ``` ### `multiple` 多日期选择 `multiple` 模式将多个日期保存在数组中,按钮文案可根据已选数量动态展示: ```vue ``` ### `buttonProps` 触发按钮 `buttonProps` 透传给触发按钮,可调整 label、color、variant 与 icon: ```vue ``` ## 示例 ### 继承字段上下文 放入 `UFormField` 后继承 `size` 与错误态,触发按钮按表单状态渲染: ```vue [ComponentsDatePickerFormFieldExample.vue] ``` ### 融入`UFieldGroup` 与按钮置于 `UFieldGroup` 时共用尺寸与边框衔接,适合筛选栏中组合快捷操作: ```vue [ComponentsDatePickerFieldGroupExample.vue] ``` ### 限制可选日期边界 `minValue` 与 `maxValue` 会禁用边界外日期,分别约束只能选择未来或过去日期: ```vue [ComponentsDatePickerValidationExample.vue] ``` ### 按规则禁用日期 `isDateUnavailable` 可按业务规则禁用日期(如示例中的周末): ```vue [ComponentsDatePickerUnavailableExample.vue] ``` ### 自定义触发按钮文案 `labelFormat` 接收格式化工具和当前值,可把日期与星期信息组合为按钮 label: ```vue [ComponentsDatePickerFormatExample.vue] ``` ### 自定义快捷预设 `presets` 传入数组可按业务规则返回日期,每项 `value` 是接收 `formatter` 的函数: ```vue [ComponentsDatePickerPresetsExample.vue] ``` ## useDateFormatter ### 用法 使用自动导入的 `useDateFormatter` composable 进行日期格式化、转换和操作,基于 `@internationalized/date` 库实现国际化日期处理。 ```vue ``` - `useDateFormatter` 基于 `Intl.DateTimeFormat` 提供本地化日期格式化。 - 支持单个日期、日期范围、日期数组以及嵌套对象的批量转换。 - 通过 `timeZone` 选项指定时区(默认本地时区),标识符遵循 IANA 时区数据库规范。 > [!NOTE] > > 所有格式化和转换方法都内置了错误处理,当传入 > > null > > 或 > > undefined > > 时会返回空字符串或 > > null > > ,避免抛出异常。 ### 能力一览 下表覆盖了 `useDateFormatter` 在常用日期场景下的输出形态: ```vue [ComposablesUseDateFormatterOverviewExample.vue] ``` ### 与 AutoForm 集成 在 AutoForm 中使用日期字段时,建议使用 `convertToISO()` 进行批量转换后提交: ```vue ``` > [!NOTE] > > convertToISO > > 自动遍历所有嵌套日期字段并保持对象结构不变,无需手动转换。 ### API #### useDateFormatter() `useDateFormatter(options?: DateFormatterOptions): DateFormatter`{lang="ts-type"} 创建日期格式化器实例。 ##### Parameters **options** (`DateFormatterOptions`): 日期格式化配置选项。语言区域,默认跟随外层 UApp,在组件外调用时使用 'en'。日期格式化选项,遵循 Intl.DateTimeFormat 规范。默认为 { dateStyle: 'medium' }。时区标识符(如 'Asia/Shanghai', 'America/New_York'),默认使用本地时区。详见 @internationalized/date 时区文档。 ##### Returns 返回包含以下方法和属性的日期格式化器对象。 #### 格式化方法 **format()** (`(date: DateValue | undefined | null) => string`): 格式化单个日期为本地化字符串。formatter.format(date) // "2025年11月29日" **formatRange()** (`(start: DateValue | undefined | null, end: DateValue | undefined | null, separator?: string) => string`): 格式化日期范围,默认分隔符为 ' - '。formatter.formatRange(startDate, endDate) // "2025年11月1日 - 2025年11月30日" formatter.formatRange(startDate, endDate, ' 至 ') // "2025年11月1日 至 2025年11月30日" **formatArray()** (`(dates: DateValue[] | undefined | null, separator?: string) => string`): 格式化日期数组,默认分隔符为 ', '。formatter.formatArray([date1, date2, date3]) // "2025年11月1日, 2025年11月15日, 2025年11月29日" #### 转换方法 **toISO()** (`(date: DateValue | undefined | null) => string`): 转换为 ISO 8601 字符串。formatter.toISO(date) // "2025-11-29" **toDate()** (`(date: DateValue | undefined | null) => Date | null`): 转换为 JavaScript Date 对象。 **toTimestamp()** (`(date: DateValue | undefined | null) => number | null`): 转换为时间戳(毫秒)。formatter.toTimestamp(date) // 1732838400000 **toUnixTimestamp()** (`(date: DateValue | undefined | null) => number | null`): 转换为 Unix 时间戳(秒)。formatter.toUnixTimestamp(date) // 1732838400 **parse()** (`(value: string) => DateValue | null`): 解析 ISO 8601 日期字符串。自动识别 CalendarDate、CalendarDateTime 或 ZonedDateTime。formatter.parse('2025-11-29') // CalendarDate formatter.parse('2025-11-29T10:30:00') // CalendarDateTime formatter.parse('2025-11-29T10:30:00[Asia/Shanghai]') // ZonedDateTime #### 工具方法 - 获取日期 **getToday()** (`() => CalendarDate`): 获取今天的日期。 **getNow()** (`() => ZonedDateTime`): 获取当前日期时间。 **getStartOfWeek()** (`(date: DateValue) => DateValue`): 获取一周的开始日期(基于当前语言区域)。 **getEndOfWeek()** (`(date: DateValue) => DateValue`): 获取一周的结束日期(基于当前语言区域)。 **getStartOfMonth()** (`(date: DateValue) => DateValue`): 获取一月的开始日期。 **getEndOfMonth()** (`(date: DateValue) => DateValue`): 获取一月的结束日期。 **getStartOfYear()** (`(date: DateValue) => DateValue`): 获取一年的开始日期。 **getEndOfYear()** (`(date: DateValue) => DateValue`): 获取一年的结束日期。 #### 工具方法 - 查询 **getDayOfWeek()** (`(date: DateValue) => number`): 获取星期几数字(0-6,0 为本地化的一周第一天)。 **getDayOfWeekName()** (`(date: DateValue, style?: 'narrow' | 'short' | 'long') => string`): 获取本地化的星期几名称。Parameters日期对象。格式样式。 默认 long'narrow' - 最短格式,如「一」'short' - 短格式,如「周一」'long' - 完整格式,如「星期一」const date = formatter.getToday() formatter.getDayOfWeekName(date, 'narrow') // "一" formatter.getDayOfWeekName(date, 'short') // "周一" formatter.getDayOfWeekName(date, 'long') // "星期一" formatter.getDayOfWeekName(date) // "星期一" (默认) **getWeeksInMonth()** (`(date: DateValue) => number`): 获取本月的周数。 **isWeekday()** (`(date: DateValue) => boolean`): 判断是否为工作日。 **isWeekend()** (`(date: DateValue) => boolean`): 判断是否为周末。 **isSameDay()** (`(a: DateValue, b: DateValue) => boolean`): 判断是否为同一天。 **isSameMonth()** (`(a: DateValue, b: DateValue) => boolean`): 判断是否为同一月。 **isSameYear()** (`(a: DateValue, b: DateValue) => boolean`): 判断是否为同一年。 **isToday()** (`(date: DateValue) => boolean`): 判断是否为今天。 **isDateValue()** (`(value: unknown) => value is DateValue`): 类型守卫,判断是否为 DateValue 类型。 **isDateRange()** (`(value: unknown) => value is DateRange`): 类型守卫,判断是否为 DateRange 类型。 #### 批量转换方法 **convertData()** (`(data: T, converter: (value: DateValue) => any) => T`): 通用数据转换函数,自动处理单个日期、日期范围、日期数组以及嵌套对象。const converted = formatter.convertData(complexData, formatter.toISO) **convertToISO()** (`(data: T) => T`): 批量转换为 ISO 字符串。支持单个日期、日期范围、数组和嵌套对象。// 单个日期 formatter.convertToISO(date) // "2025-11-29" // 日期范围 formatter.convertToISO({ start: date1, end: date2 }) // { start: "2025-11-01", end: "2025-11-30" } // 日期数组 formatter.convertToISO([date1, date2]) // ["2025-11-01", "2025-11-15"] // 嵌套对象 formatter.convertToISO({ createdAt: date1, range: { start: date2, end: date3 } }) // { // createdAt: "2025-11-01", // range: { start: "2025-11-20", end: "2025-11-29" } // } **convertToFormatted()** (`(data: T) => T`): 批量转换为格式化字符串。 **convertToDate()** (`(data: T) => T`): 批量转换为 Date 对象。 #### 配置属性 **locale** (`string`): 当前使用的语言区域。 **timeZone** (`string`): 当前使用的时区。 ### Changelog See commit history for [src/runtime/composables/datePicker.ts](https://github.com/mhaibaraai/movk-nuxt/commits/main/src/runtime/composables/datePicker.ts). ### 控制日历开关 `v-model:open` 同步弹层状态,也可调用实例的 `open()` 和 `close()`。旧 `popoverProps.open` 作为次级控制,`popoverProps.defaultOpen` 只用于初始化非受控状态。 ```vue [ComponentsDatePickerOpenExample.vue] ``` ## API ### Props ```ts /** * Props for the MDatePicker component */ interface MDatePickerProps { id?: string | undefined; name?: string | undefined; /** * 同时作用于触发按钮与日历,缺省时继承 UFormField / UFieldGroup */ size?: "xs" | "sm" | "md" | "lg" | "xl" | undefined; /** * 日历主色;处于表单错误态时触发按钮显示为 error */ color?: "primary" | "secondary" | "info" | "success" | "warning" | "error" | "important" | "neutral" | undefined; disabled?: boolean | undefined; /** * 未选择时的按钮文本,缺省时依次取 `buttonProps.label`、locale 的 `datePicker.placeholder` */ placeholder?: string | undefined; buttonProps?: ButtonProps | undefined; popoverProps?: PopoverProps

| undefined; /** * @default 'formatted' */ labelFormat?: "iso" | "timestamp" | "unix" | "date" | "formatted" | (formatter: { format: (date: Nullable) => string; formatRange: (start: Nullable, end: Nullable, separator?: string) => string; ... 38 more ...; timeZone: string; }, modelValue: CalendarModelValue<...> | undefined): string | undefined; /** * v-model 投影输出格式 * @default 'date-value' */ valueFormat?: V | undefined; clearable?: boolean | undefined; /** * 快捷预设 */ presets?: "default" | DatePickerPreset[] | undefined; ui?: Record & { content?: SlotClass; arrow?: SlotClass; wrapper?: SlotClass; presets?: SlotClass; presetButton?: SlotClass; calendar?: SlotClass; clearIcon?: SlotClass; } | undefined; /** * 语言区域,缺省时跟随 ``,组件外调用时为 `'en'` */ locale?: string | undefined; /** * 日期格式化选项 */ formatOptions?: Intl.DateTimeFormatOptions | undefined; /** * 时区标识符,默认使用本地时区 */ timeZone?: string | undefined; /** * The element or component this component should render as. * @default 'div' */ as?: any; /** * The type of picker. * - `date` renders a day calendar whose heading can switch to a month then year view. * - `month` renders a standalone month picker. * - `year` renders a standalone year picker. * @default 'date' */ type?: "date" | "month" | "year" | undefined; /** * The icon to use for the next year control. * @default appConfig.ui.icons.chevronDoubleRight */ nextYearIcon?: any; /** * Configure the next year button. * `{ color: 'neutral', variant: 'ghost' }`{lang="ts-type"} */ nextYear?: Omit | undefined; /** * The icon to use for the next month control. * @default appConfig.ui.icons.chevronRight */ nextMonthIcon?: any; /** * Configure the next month button. * `{ color: 'neutral', variant: 'ghost' }`{lang="ts-type"} */ nextMonth?: Omit | undefined; /** * The icon to use for the previous year control. * @default appConfig.ui.icons.chevronDoubleLeft */ prevYearIcon?: any; /** * Configure the prev year button. * `{ color: 'neutral', variant: 'ghost' }`{lang="ts-type"} */ prevYear?: Omit | undefined; /** * The icon to use for the previous month control. * @default appConfig.ui.icons.chevronLeft */ prevMonthIcon?: any; /** * Configure the prev month button. * `{ color: 'neutral', variant: 'ghost' }`{lang="ts-type"} */ prevMonth?: Omit | undefined; /** * Whether to make the heading a button that switches between the day, month and year views. * Has no effect when `type` is `year`. Can be an object to override the button props. * `{ color: 'neutral', variant: 'ghost', block: true }`{lang="ts-type"} * @default true */ viewControl?: boolean | Omit | undefined; /** * @default 'solid' */ variant?: "solid" | "outline" | "soft" | "subtle" | undefined; /** * Whether or not a range of dates can be selected */ range?: R | undefined; /** * Whether or not multiple dates can be selected */ multiple?: M | undefined; /** * Show month controls */ monthControls?: boolean | undefined; /** * Show year controls */ yearControls?: boolean | undefined; defaultValue?: CalendarDefaultValue | undefined; weekNumbers?: boolean | undefined; /** * The default placeholder date */ defaultPlaceholder?: CalendarDate | CalendarDateTime | ZonedDateTime | undefined; /** * When combined with `isDateUnavailable`, determines whether non-contiguous ranges, i.e. ranges containing unavailable dates, may be selected. */ allowNonContiguousRanges?: boolean | undefined; /** * This property causes the previous and next buttons to navigate by the number of months displayed at once, rather than one month */ pagedNavigation?: boolean | undefined; /** * Whether or not to prevent the user from deselecting a date without selecting another date first */ preventDeselect?: boolean | undefined; /** * The maximum number of days that can be selected in a range */ maximumDays?: number | undefined; /** * The day of the week to start the calendar on */ weekStartsOn?: 0 | 1 | 2 | 4 | 5 | 3 | 6 | undefined; /** * The format to use for the weekday strings provided via the weekdays slot prop */ weekdayFormat?: "narrow" | "short" | "long" | undefined; /** * Whether or not to always display 6 weeks in the calendar */ fixedWeeks?: boolean | undefined; /** * The maximum date that can be selected */ maxValue?: CalendarDate | CalendarDateTime | ZonedDateTime | undefined; /** * The minimum date that can be selected */ minValue?: CalendarDate | CalendarDateTime | ZonedDateTime | undefined; /** * The number of months to display at once */ numberOfMonths?: number | undefined; /** * Whether or not the calendar is readonly */ readonly?: boolean | undefined; /** * If true, the calendar will focus the selected day, today, or the first day of the month depending on what is visible when the calendar is mounted */ initialFocus?: boolean | undefined; /** * A function that returns whether or not a date is disabled */ isDateDisabled?: (date: DateValue): boolean | undefined; /** * A function that returns whether or not a date is unavailable */ isDateUnavailable?: (date: DateValue): boolean | undefined; /** * A function that returns whether or not a date is hightable */ isDateHighlightable?: (date: DateValue): boolean | undefined; /** * A function that returns the next page of the calendar. It receives the current placeholder as an argument inside the component. */ nextPage?: (placeholder: DateValue): DateValue | undefined; /** * A function that returns the previous page of the calendar. It receives the current placeholder as an argument inside the component. */ prevPage?: (placeholder: DateValue): DateValue | undefined; /** * Whether or not to disable days outside the current view. */ disableDaysOutsideCurrentView?: boolean | undefined; /** * Which part of the range should be fixed */ fixedDate?: "start" | "end" | undefined; /** * A function that returns whether or not a month is disabled */ isMonthDisabled?: (date: DateValue): boolean | undefined; /** * A function that returns whether or not a month is unavailable */ isMonthUnavailable?: (date: DateValue): boolean | undefined; /** * A function that returns whether or not a year is disabled */ isYearDisabled?: (date: DateValue): boolean | undefined; /** * A function that returns whether or not a year is unavailable */ isYearUnavailable?: (date: DateValue): boolean | undefined; /** * Number of years to display per page */ yearsPerPage?: number | undefined; modelValue?: FormattedValue | undefined; /** * @default undefined */ open?: boolean | undefined; } ``` ### Emits ```ts /** * Emitted events for the MDatePicker component */ interface MDatePickerEmits { close:prevent: (payload: []) => void; update:modelValue: (payload: [value: FormattedValue]) => void; update:placeholder: (payload: [date: DateValue]) => void; update:validModelValue: (payload: [date: DateRange]) => void; update:startValue: (payload: [date: DateValue | undefined]) => void; update:open: (payload: [value: boolean | undefined]) => void; update:modelValue: (payload: [value: FormattedValue | undefined]) => void; } ``` ### Slots ```ts /** * Slots for the MDatePicker component */ interface MDatePickerSlots { default(): any; content(): any; heading(): any; day(): any; week-day(): any; month-cell(): any; year-cell(): any; leading(): any; trailing(): any; } ``` ## Theme ::component-theme :: ## Changelog See commit history for [src/runtime/components/DatePicker.vue](https://github.com/mhaibaraai/movk-nuxt/commits/main/src/runtime/components/DatePicker.vue). # MessageBox > 模态消息对话框,提供声明式与编程式两种调用方式。 ## 简介 `MMessageBox` 是一个模态对话框组件,适用于重要通知或需要用户明确确认的场景。提供 `alert` 与 `confirm` 两种模式,内置六种语义化类型,并支持通过 `useMessageBox()` 进行编程式调用。 > [!NOTE] > See: https://ui.nuxt.com/docs/components/modal > > 基于 Nuxt UI 的 Modal 组件封装 ## 用法 `default` 插槽放置触发元素,组件内部由 `UModal` 自动管理打开状态: ```vue ``` ### `mode` 模式 `alert` 仅显示确认按钮,`confirm` 同时提供取消与确认并返回布尔结果: ```vue ``` ### `type` 类型 `type` 影响默认图标与确认按钮颜色,包含六种语义化值: ```vue ``` ### `icon` 图标 `icon` 覆盖 `type` 默认图标,传入任意 Iconify 图标名称: ```vue ``` ### `label` 文案 `alertConfirmLabel` 控制 `alert` 模式按钮文案,`confirmLabel` 与 `cancelLabel` 分别覆盖 `confirm` 模式的两个按钮: ```vue ``` ### `buttonProps` 按钮属性 `confirmButton` 与 `cancelButton` 接收完整 `ButtonProps`,可定制 icon、color、variant 与 label: ```vue ``` ### `dismissible` 关闭策略 `dismissible` 默认为 `false` 严格模式;开启后允许点击遮罩或按 Esc 关闭,并通过 `close(false)` 标记为未确认: ```vue ``` ## 示例 ### 受控状态 通过 `v-model:open` 外部控制开关,适合编程式触发与多按钮联动: ```vue [ComponentsMessageBoxControlledExample.vue] ``` ### 正文插槽 `body` 插槽渲染富文本正文,slot 参数 `close` 可在正文内主动关闭弹窗: ```vue [ComponentsMessageBoxBodySlotExample.vue] ``` ### 标题插槽 `title` 插槽完全接管标题区,覆盖默认的图标加文本组合: ```vue [ComponentsMessageBoxTitleSlotExample.vue] ``` ### 描述插槽 `description` 插槽支持富文本描述,可与 `title` prop 配合工作: ```vue [ComponentsMessageBoxDescriptionSlotExample.vue] ``` ### 头部插槽 `header` 插槽完整接管 title 与 description 容器,可自定义布局与排版: ```vue [ComponentsMessageBoxHeaderSlotExample.vue] ``` ### 操作插槽 `footer` 插槽完全接管按钮区,slot 参数 `close` 用于关闭弹窗: ```vue [ComponentsMessageBoxFooterSlotExample.vue] ``` ### 关闭按钮插槽 `close` 插槽自定义右上角关闭按钮,可改 icon、color 与样式: ```vue [ComponentsMessageBoxCloseSlotExample.vue] ``` ### 内容插槽 `content` 插槽替代 header / body / footer 的整体布局,适合极致定制场景: ```vue [ComponentsMessageBoxContentSlotExample.vue] ``` ### 命令式调用 使用 `useMessageBox()` 在任意逻辑中调用对话框,无需在模板中声明组件。`alert()` 返回 `Promise`,`confirm()` 返回 `Promise`: ```vue [ComponentsMessageBoxProgrammaticExample.vue] ``` ## useMessageBox ### 简介 `useMessageBox` 提供命令式弹窗 API,无需在模板中声明组件即可弹出对话框。它基于 [`MessageBox`](https://nuxt.mhaibaraai.me/docs/components/message-box) 组件与 Nuxt UI 的 `useOverlay` 实现。 ```ts const { alert, confirm } = useMessageBox() ``` 两个方法的入参均为 `MessageBox` 的 props(`mode` 由方法自动设置):`title`、`description`、`type`、`icon`、按钮配置等,详见组件文档。 ### alert `alert(options)` 弹出仅含确认动作的提示框,返回 Promise,用户关闭后才 resolve,适合阻塞式提示: ```ts const { alert } = useMessageBox() async function onSave() { await save() await alert({ type: 'success', title: '保存成功' }) // 用户关闭弹窗后继续 } ``` ```vue [ComposablesUseMessageBoxAlertExample.vue] ``` ### confirm `confirm(options)` 返回 `Promise`,把确认/取消映射为布尔值: ```ts const { confirm } = useMessageBox() async function onDelete() { const ok = await confirm({ type: 'warning', title: '删除确认', description: '该操作不可恢复,确定继续?' }) if (!ok) return await remove() } ``` ```vue [ComposablesUseMessageBoxConfirmExample.vue] ``` ### 异步确认流程 `confirm` 适合串联异步流程——确认后再执行耗时任务: ```vue [ComposablesUseMessageBoxAsyncExample.vue] ``` > [!TIP] > See: /docs/components/message-box > > 声明式用法与完整 props 见 MessageBox 组件文档。 ## API ### Props ```ts /** * Props for the MMessageBox component */ interface MMessageBoxProps { /** * 模态框标题文本,缺省时取 locale 的 `messageBox.title`。 */ title?: string | undefined; /** * 控制消息框的语义类型。 * 会影响默认图标与确认按钮颜色。 * @default 'primary' */ type?: "primary" | "info" | "success" | "warning" | "error" | "neutral" | undefined; /** * 标题前展示的图标名称,缺省时按 `type` 取对应图标。 */ icon?: any; /** * 控制消息框的操作模式。 * `alert` 仅显示确认按钮,`confirm` 显示取消与确认按钮。 * @default 'alert' */ mode?: "alert" | "confirm" | undefined; /** * 当 `false` 时,点击遮罩层或按下 `Esc` 键将不会关闭模态框。 * @default false */ dismissible?: boolean | undefined; /** * alert 模式下的确认按钮文本,缺省时取 locale 的 `messageBox.acknowledge`。 */ alertConfirmLabel?: string | undefined; /** * 确认按钮文本,缺省时取 locale 的 `messageBox.confirm`。 */ confirmLabel?: string | undefined; /** * 取消按钮文本,缺省时取 locale 的 `messageBox.cancel`。 */ cancelLabel?: string | undefined; /** * 透传给确认按钮的属性。 * 未显式指定 `color` 时会默认继承当前 `type`。 */ confirmButton?: ButtonProps | undefined; /** * 透传给取消按钮的属性。 * 仅在 `mode='confirm'` 时渲染。 */ cancelButton?: ButtonProps | undefined; ui?: Record & { overlay?: SlotClass; content?: SlotClass; header?: SlotClass; wrapper?: SlotClass; body?: SlotClass; footer?: SlotClass; title?: SlotClass; description?: SlotClass; close?: SlotClass; icon?: SlotClass; } | undefined; description?: string | undefined; /** * The content of the modal. */ content?: Omit & Partial> | undefined; /** * Render an overlay behind the modal. * @default true */ overlay?: boolean | undefined; /** * When `true`, enables scrollable overlay mode where content scrolls within the overlay. * @default false */ scrollable?: boolean | undefined; /** * Animate the modal when opening or closing. * @default true */ transition?: boolean | undefined; /** * When `true`, the modal will take up the full screen. * @default false */ fullscreen?: boolean | undefined; /** * Render the modal in a portal. * @default true */ portal?: string | false | true | HTMLElement | undefined; /** * Display a close button to dismiss the modal. * `{ size: 'md', color: 'neutral', variant: 'ghost' }`{lang="ts-type"} * @default true */ close?: boolean | Omit | undefined; /** * The icon displayed in the close button. * @default appConfig.ui.icons.close */ closeIcon?: any; /** * The modality of the dialog When set to `true`,
* interaction with outside elements will be disabled and only dialog content will be visible to screen readers. */ modal?: boolean | undefined; /** * When set to `false`, the dialog content will not be unmounted when closed, but instead hidden with CSS.
* Useful for SEO or when you want to improve performance by not remounting the component on every open. * @default true */ unmountOnHide?: boolean | undefined; open?: boolean | undefined; } ``` ### Emits ```ts /** * Emitted events for the MMessageBox component */ interface MMessageBoxEmits { update:open: (payload: [value: boolean | undefined]) => void; close: (payload: [confirmed: boolean]) => void; } ``` ### Slots ```ts /** * Slots for the MMessageBox component */ interface MMessageBoxSlots { default(): any; content(): any; header(): any; title(): any; description(): any; actions(): any; close(): any; body(): any; footer(): any; } ``` ## Theme ::component-theme :: ## Changelog See commit history for [src/runtime/components/MessageBox.vue](https://github.com/mhaibaraai/movk-nuxt/commits/main/src/runtime/components/MessageBox.vue). # Tree > 基于 Nuxt UI Tree 的树形组件,补齐搜索、懒加载、工具栏、复选框与父子策略。 ## 简介 `MTree` 在 Nuxt UI `Tree` 之上做薄壳封装,透传其全部 props、事件与插槽,并补齐多项增强能力:搜索过滤与高亮、异步懒加载、工具栏(展开/折叠切换、三态全选)、复选框多选与父子策略(级联 / 互不关联)、键绑定(`v-model:selectedKeys`)以及命令式 API 与选中分类。树形数据的归一化、过滤、遍历等运算复用 `@movk/core` 的 `Tree` 工具方法。 > [!NOTE] > See: https://ui.nuxt.com/docs/components/tree > > 基于 Nuxt UI 的 Tree 组件构建,原生 props 与插槽完全透传 ## 用法 传入 `items` 渲染层级结构,节点 `defaultExpanded` 控制初始展开,`v-model` 绑定选中节点: ```vue ``` ### `defaultExpanded` 默认展开 `defaultExpanded` 作用:以策略推导初始展开的父节点,缺省回退节点上的 `defaultExpanded` 标记。传 `true` 展开全部父级、传 `number` 仅展开 depth 小于该值的父级、传函数按节点与深度自定义: ```vue ``` ### `searchable` 搜索过滤 `searchable` 作用:在顶部渲染搜索框,按关键字剪枝并保留命中节点的祖先链;`highlight` 默认开启,高亮命中文本,命中后自动展开。`filter` 可自定义匹配谓词,`search` 支持 `v-model:search` 双向绑定关键字: ```vue ``` ### `checkable` 复选框级联 `checkable` 作用:在节点前渲染复选框,内部启用 `multiple` 与父子级联、子级半选冒泡,`v-model` 收集选中节点数组。复选框与节点 `icon`、父节点 folder 图标共存: ```vue ``` > [!NOTE] > > checkable > > 等价于 > > multiple > > + > > strategy > > (默认 > > cascade > > )的语法糖。仅需多选而不渲染复选框时改用 > > multiple > > 。 ### `multiple` 多选 `multiple` 作用:开启多选但不渲染复选框,点击节点累加选中,`v-model` 收集选中节点数组: ```vue ``` ### `strategy` 父子策略 `strategy` 作用:控制多选 / `checkable` 下的父子勾选关系。`cascade`(默认)父子级联且子级全选时回填父级,`isolated` 父子互不关联、半选不冒泡: ```vue ``` ### `selectedKeys` 键绑定 `selectedKeys` 作用:以节点 key 数组双向绑定选中,适合从后端回显或与路由同步。`v-model:selectedKeys` 与 `v-model` 互通,键由 `getKey` / `labelKey` 派生: ```vue ``` ### `toolbar` 工具栏 `toolbar` 作用:渲染顶部工具栏,提供展开 / 折叠切换按钮;`searchable` 时内嵌可清除的搜索框,`checkable` 时附带三态全选复选框与选中计数: ```vue ``` > [!NOTE] > > 工具栏的全选计数按 > > 叶子 > > 计:级联下选中父级会带上子级 key,按叶子统计可避免重复计数。 ### `lazy` 异步懒加载 `lazy` 作用:配合 `loadChildren`,展开未加载的父节点时拉取子节点并显示加载态;节点 `isLeaf` 标记为叶子,不渲染展开占位: ```vue [ComponentsTreeLazyExample.vue] ``` ### `childrenKey` 字段映射 `childrenKey` 作用:将后端的子节点字段归一化为 `children`,`labelKey` 指定展示字段,无需预先改造数据结构: ```vue ``` ### `labelKey` 点路径取值 `labelKey` 作用:指定节点展示字段,支持 `meta.title` 形式的点路径深取嵌套字段;键派生、搜索与高亮均按同一路径取值: ```vue ``` > [!NOTE] > > 点路径需与 UTree 内部取值一致,仅支持点分隔( > > a.b.c > > ),不支持括号下标( > > a[0].b > > )。 ### `virtualize` 虚拟滚动 `virtualize` 作用:透传 Nuxt UI Tree 的虚拟化能力,仅渲染可视区节点,适配大数据量树: ```vue [ComponentsTreeVirtualizeExample.vue] ``` ### `color` 主色 `color` 作用:透传 Nuxt UI Tree 的主色,作用于选中节点的文字色与键盘聚焦环;下例预选一个节点以便观察: ```vue ``` > [!NOTE] > > UTree 的 > > color > > 仅作用于选中节点文字与焦点环;未选中任何节点时不会有可见变化。单色图标(如 lucide)随文字色继承,多色图标(如 vscode-icons)保持自身配色。 ### `trailingIcon` 末尾图标 `trailingIcon` 作用:替换父节点末尾的展开指示图标(默认 `i-lucide-chevron-down`);节点数据的 `item.trailingIcon` 优先级更高: ```vue ``` ### `expandedIcon` 展开图标 `expandedIcon` / `collapsedIcon` 作用:自定义父节点展开 / 折叠时的 leading 图标(默认 `i-lucide-folder-open` / `i-lucide-folder`): ```vue ``` > [!NOTE] > > 节点的 > > item.icon > > 优先级高于 > > expandedIcon > > / > > collapsedIcon > > ,故需要随展开态切换图标的文件夹不应设置 > > item.icon > > 。 ### `disabled` 禁用 `disabled` 作用:禁用整棵树,阻断点击节点、工具栏控件与复选框的展开、折叠、选中操作;节点级 `item.disabled` 连同其整棵子树一并禁用——冻结该节点展开态,子树内复选框禁用且不可选中: ```vue ``` > [!NOTE] > > 命令式 API( > > expandToDepth > > 、 > > selectAll > > 等)属显式调用,不受 > > disabled > > 影响; > > disabled > > 仅拦截用户的点击与工具栏交互。 ## 示例 ### 自定义节点 通过透传的 `item-trailing` 等插槽自定义节点内容,未覆盖的插槽仍由 Nuxt UI Tree 默认渲染: ```vue [ComponentsTreeSlotExample.vue] ``` ### 自定义工具栏 `toolbar-leading` / `toolbar-trailing` 在默认工具栏首尾追加内容;需要完全接管时改用 `#toolbar` 插槽,其作用域暴露 `toggleExpand`、`selectAll`、`clear`、`selectionSummary` 等方法与状态: ```vue [ComponentsTreeCustomToolbarExample.vue] ``` ### 命令式控制 通过 `useTemplateRef` 拿到组件实例,调用 `expandToDepth`、`collapseAll`、`selectAll`、`clearSelection` 等方法控制树: ```vue [ComponentsTreeImperativeExample.vue] ``` ### 选中结果分类 实例的 `treeSelection` 反应式回传选中分类:`leaves`(选中叶子)、`parents`(满选父级)、`halfSelected`(半选父级)、`strictlyChecked`(剔除随父级联的子节点): ```vue [ComponentsTreeSelectionExample.vue] ``` ### 远程搜索与重载 `searchMethod` 返回匹配节点,`searchDebounce` 默认 300 ms。已选远程节点跨搜索保留。失败时可重试,`searchError` 返回关键字和错误。`reload(key)` 重载懒加载分支,`reload()` 按 `items` 重建。`getNode(key)` 可查询当前和仍选中的远程节点。`leaf` 策略按叶子归类。 ```vue [ComponentsTreeRemoteSearchExample.vue] ``` ## API ### Props ```ts /** * Props for the MTree component */ interface MTreeProps { /** * 树数据源,按 childrenKey 解析层级 */ items?: T | undefined; /** * 取子节点数组的字段名,归一化为 UTree 的 children * @default 'children' */ childrenKey?: string | undefined; /** * 展示字段名 * @default 'label' */ labelKey?: keyof Extract, object> & string | DotPathKeys, object>> | undefined; /** * 自定义节点 key,缺省取 labelKey 字段值 */ getKey?: (val: T[number]): string | undefined; /** * 初始展开策略,缺省回退节点上的 defaultExpanded 标记 * - true 展开全部父级 * - number 展开 depth 小于该值的父级 * - 函数 按节点与深度自定义 */ defaultExpanded?: number | false | true | (node: T[number], depth: number): boolean | undefined; /** * 选中节点 key 列表,可用 v-model:selectedKeys 双向绑定 */ selectedKeys?: string[] | undefined; /** * 开启多选 */ multiple?: M | undefined; /** * 多选 / checkable 下的父子勾选策略 * - 'cascade' 父子级联(propagateSelect + bubbleSelect) * - 'isolated' 父子互不关联 * - 'leaf' 交互同 cascade,`change` 与 `treeSelection` 以叶子为准 * @default 'cascade' */ strategy?: "cascade" | "isolated" | "leaf" | undefined; /** * 选中父节点时级联选中子节点。cascade 策略下默认开启,显式 true 可在 isolated 下强制开启;关闭级联请用 strategy='isolated' */ propagateSelect?: boolean | undefined; /** * 子节点全部选中时回填父节点。cascade 策略下默认开启,显式 true 可在 isolated 下强制开启;关闭级联请用 strategy='isolated' */ bubbleSelect?: boolean | undefined; /** * 尺寸 * @default 'md' */ size?: "md" | "xs" | "sm" | "lg" | "xl" | undefined; /** * 主色 * @default 'primary' */ color?: "primary" | "secondary" | "info" | "success" | "warning" | "error" | "important" | "neutral" | undefined; /** * 父节点展开时的图标 * @default 取 app.config 的 ui.icons.folderOpen */ expandedIcon?: any; /** * 父节点折叠时的图标 * @default 取 app.config 的 ui.icons.folder */ collapsedIcon?: any; /** * 禁用整棵树,阻断点击、工具栏与复选框的展开、折叠、选中 */ disabled?: boolean | undefined; /** * 开启顶部搜索过滤 */ searchable?: boolean | undefined; /** * 自定义匹配谓词,缺省按 labelKey 文本不区分大小写包含匹配 */ filter?: (node: T[number], term: string): boolean | undefined; /** * 远程搜索:返回命中的节点树,设置后忽略 `filter` */ searchMethod?: (term: string): Promise | undefined; /** * 远程搜索的防抖时长(ms) * @default 300 */ searchDebounce?: number | undefined; /** * 高亮命中文本,仅在 searchable 时生效 * @default true */ highlight?: boolean | undefined; /** * 开启异步懒加载子节点 */ lazy?: boolean | undefined; /** * 懒加载回调,展开未加载的父节点时调用 */ loadChildren?: (node: T[number]): Promise | undefined; /** * 开启顶部工具栏(展开/折叠,checkable 时附带全选/清空) */ toolbar?: boolean | undefined; /** * 渲染复选框并启用多选(multiple + strategy,默认 cascade) */ checkable?: M | undefined; ui?: Record & { root?: SlotClass; item?: SlotClass; listWithChildren?: SlotClass; itemWithChildren?: SlotClass; link?: SlotClass; linkLeadingIcon?: SlotClass; linkLabel?: SlotClass; linkTrailing?: SlotClass; linkTrailingIcon?: SlotClass; container?: SlotClass; toolbar?: SlotClass; toolbarButton?: SlotClass; search?: SlotClass; checkbox?: SlotClass; highlight?: SlotClass; loading?: SlotClass; loadingIcon?: SlotClass; empty?: SlotClass; } | undefined; /** * The element or component this component should render as. * @default 'ul' */ as?: any; /** * The icon displayed on the right side of a parent node. * @default appConfig.ui.icons.chevronDown */ trailingIcon?: any; /** * The controlled value of the Tree. Can be bind as `v-model`. */ modelValue?: M extends true ? T[number][] : T[number] | undefined; /** * The value of the Tree when initially rendered. Use when you do not need to control the state of the Tree. */ defaultValue?: M extends true ? T[number][] : T[number] | undefined; /** * Use nested DOM structure (children inside parents) vs flattened structure (all items at same level). * When `virtualize` is enabled, this is automatically set to `false`. * @default true */ nested?: boolean | undefined; /** * Enable virtualization for large lists. * Note: when enabled, the tree structure is flattened like if `nested` was set to `false`. * @default false */ virtualize?: boolean | { overscan?: number | undefined; estimateSize?: number | ((index: number) => number) | undefined; } | undefined; onSelect?: (e: SelectEvent, item: T[number]): void | undefined; onToggle?: (e: ToggleEvent, item: T[number]): void | undefined; /** * The controlled value of the expanded item. Can be binded with `v-model`. * @default [] */ expanded?: string[] | undefined; /** * How multiple selection should behave in the collection. */ selectionBehavior?: "replace" | "toggle" | undefined; /** * When `true`, keyboard navigation will loop from last item to first, and vice versa. */ loop?: boolean | undefined; /** * @default '' */ search?: string | undefined; } ``` ### Emits ```ts /** * Emitted events for the MTree component */ interface MTreeEmits { update:modelValue: (payload: [val: M extends true ? T[number][] : T[number]]) => void; update:expanded: (payload: [val: string[]]) => void; update:search: (payload: [value: string]) => void; loadError: (payload: [node: T[number], error: unknown]) => void; searchError: (payload: [term: string, error: unknown]) => void; change: (payload: [payload: { value: (M extends true ? T[number][] : T[number]) | undefined; keys: string[]; selection: TreeSelectionResult; }]) => void; update:modelValue: (payload: [value: (M extends true ? T[number][] : T[number]) | undefined]) => void; update:selectedKeys: (payload: [value: string[] | undefined]) => void; } ``` > [!TIP] > > 除透传 Nuxt UI Tree 的 `update:modelValue`、`update:expanded` 外,`MTree` 额外提供: > > - `update:search`:搜索关键字变化时触发,支持 `v-model:search`。 > - `update:selectedKeys`:选中 key 列表变化时触发,支持 `v-model:selectedKeys`。 > - `change`:选中变化时触发,载荷为 `{ value, keys, selection }`,`keys` 由 `getKey`/`labelKey` 派生,`selection` 为选中结果分类。 ### Slots ```ts /** * Slots for the MTree component */ interface MTreeSlots { item-wrapper(): any; item(): any; item-leading(): any; item-label(): any; item-trailing(): any; toolbar(): any; /** * 默认工具栏起始处追加内容 */ toolbar-leading(): any; /** * 默认工具栏末尾追加内容 */ toolbar-trailing(): any; empty(): any; loading(): any; } ``` ### Expose 您可以通过 [`useTemplateRef`](https://vuejs.org/api/composition-api-helpers.html#usetemplateref) 访问该类型化组件实例。 | Name | Type | | --- | --- | | `expandAll()` | `void`
展开全部可展开节点 | | `collapseAll()` | `void`
收起全部节点 | | `expandToDepth(depth)` | `void`
展开到指定层级,`depth=0` 收起全部 | | `selectAll()` | `void`
选中全部可选节点 | | `clearSelection()` | `void`
清空选中 | | `treeSelection` | `TreeSelectionResult`
当前选中结果分类(`selected` / `leaves` / `parents` / `halfSelected` / `strictlyChecked`) | ## Theme ::component-theme :: ## Changelog See commit history for [src/runtime/components/Tree.vue](https://github.com/mhaibaraai/movk-nuxt/commits/main/src/runtime/components/Tree.vue). # Movk Nuxt > 面向 Nuxt 与 Vue 的应用开发工具包,提供 Schema 驱动的表单、可配置的数据表格、独立组件和组合式函数,支持在 Nuxt 中接入 API。 ::home :: ## Resources for Agents - [API catalog: every service document this site publishes](https://nuxt.mhaibaraai.me/.well-known/api-catalog) - [Sitemap (XML)](https://nuxt.mhaibaraai.me/sitemap.xml) - [Sitemap (Markdown): every page on the site](https://nuxt.mhaibaraai.me/sitemap.md) - [MCP server card: MCP endpoint at https://nuxt.mhaibaraai.me/mcp](https://nuxt.mhaibaraai.me/.well-known/mcp/server-card.json) - [MCP endpoint (streamable HTTP)](https://nuxt.mhaibaraai.me/mcp) - [llms.txt: index of the documentation for LLMs](https://nuxt.mhaibaraai.me/llms.txt) - [llms-full.txt: the full documentation as a single file](https://nuxt.mhaibaraai.me/llms-full.txt) - [Agent skills index: every skill published by this site](https://nuxt.mhaibaraai.me/.well-known/skills/index.json) - [Agent skill: movk-nuxt](https://nuxt.mhaibaraai.me/.well-known/skills/movk-nuxt/SKILL.md) - [Documentation](https://nuxt.mhaibaraai.me/docs) - [Homepage](https://nuxt.mhaibaraai.me/raw/index.md) # Introduction > Explore forms, data tables, components, and API integration in Movk Nuxt and choose a setup for Nuxt or Vue + Vite. ## Introduction Movk Nuxt is an **application toolkit for Nuxt and Vue**. Built on [Nuxt UI](https://ui.nuxt.com), it provides AutoForm, DataTable, standalone components, and composables. Start with a single component or combine forms, tables, and theming. In Nuxt, you can also integrate API requests, authentication, and file transfers. It offers **two modes of use**: - **Nuxt 4** — Get full capabilities including API integration (auth, progress tracking). - **Plain Vue + Vite** — Via `@movk/nuxt/vite` + `@movk/nuxt/vue-plugin`, use its UI layer: standalone components, AutoForm, DataTable, theming and non-server-side composables. **The API integration domain depends on the Nuxt server runtime and is only available in Nuxt mode.** > [!NOTE] > > Follows > > progressive adoption > > principles — you can use just the date utilities or UI components, use fully automated > > AutoForm > > , integrate the > > API System > > in Nuxt, or bring its UI layer into a plain Vue + Vite project (see > > Vue / Vite > > ). ## Core Features **Schema-Driven Forms · Nuxt / Vue+Vite** AutoForm automatically generates complete form interfaces from a Zod Schema — one Schema simultaneously defines data structure, validation rules and UI configuration. **Type-Safe Table · Nuxt / Vue+Vite** DataTable provides data, selection, index, expand and action column types, with sorting, column pinning, tree data, pagination and load-more support. **Standalone Components & Utilities · Nuxt / Vue+Vite** Components like DatePicker , SearchForm , Tree and MessageBox , along with composables like useDateFormatter , useTheme and useMessageBox , can all be used independently. **API Integration System · Nuxt Only** The useApiFetch family wraps multi-endpoint, auto-auth, business status code checking and Toast notifications, plus file upload/download with progress (requires Nuxt server runtime). ## Architecture Layers Movk Nuxt uses a clear layered architecture: > [!NOTE] > > **Architecture Levels** > > - **Core Systems** - AutoForm (schema-driven forms), DataTable (type-safe tables) > - **API System** - useApiFetch, useLazyApiFetch, useClientApiFetch, useUploadWithProgress, useDownloadWithProgress > - **Standalone Components** - DatePicker, SearchForm, Tree, MessageBox, ThemePicker > - **Composables** - useDateFormatter, useAutoForm, useTheme, useMessageBox and other general-purpose composables > - **Vite/Vue Compatibility Layer** - `@movk/nuxt/vite` + `@movk/nuxt/vue-plugin`, making the UI layer (Core Systems, Standalone Components, non-server composables) available in plain Vue + Vite (excludes API System) > - **Foundation** - Based on [Nuxt UI](https://ui.nuxt.com), [Zod v4](https://zod.dev), [VueUse](https://vueuse.org) ## Core Modules ### AutoForm - Schema-Driven Form System A "define and render" form solution based on Zod Schema, supporting multiple control types, layout systems, conditional linking and other advanced features. > [!TIP] > See: /en/docs/auto-form/quickstart > > Deep dive into AutoForm's core concepts and usage ### DataTable - Type-Safe Data Table A declarative column configuration table based on `@tanstack/vue-table`, supporting data, selection, index, expand and action column types, as well as sorting, column pinning, drag-to-resize, tree data, pagination and load-more. > [!TIP] > See: /en/docs/data-table > > Learn about DataTable's column configuration and advanced features ### API System - Unified Requests & Auth Provides a complete API request solution: - `useApiFetch` - Wraps useFetch with auto-auth, business status code checking and Toast notifications - `useUploadWithProgress` / `useDownloadWithProgress` - File upload/download with progress monitoring > [!TIP] > See: /en/docs/api > > Learn how to use the API System ### Standalone Components - Ready to Use High-quality UI components that can be used directly without AutoForm: - `DatePicker` - Internationalization-standard date picker (single / range / multiple) - `Tree` - Tree with checking, search and lazy loading - `MessageBox` - Imperative confirm/alert dialog > [!TIP] > See: /en/docs/components/date-picker > > Browse all available components ### General Utilities - `useDateFormatter` - Date formatting, parsing and range processing utilities - `useAutoForm` - Core logic wrapper for AutoForm - `useTheme` - Theme state reading/writing with CSS/config export - `useMessageBox` - Imperative alert / confirm dialogs > [!TIP] > See: /en/docs/auto-form/use-auto-form > > View all Composables # Installation > Install and configure the Movk Nuxt module in a Nuxt 4 project. > [!NOTE] > See: /en/docs/getting-started/vue > > Using > > Vue + Vite > > (non-Nuxt)? See the Vue / Vite mode instructions. ## Requirements > [!NOTE] > > - **Node.js** - `^22.22.3 || ^24.15.0 || >=26.0.0` > - **Nuxt** - `^4.6.4` (requires Nuxt 4) > - **Nuxt UI** - `>=4.13.0` > - **Package manager** - pnpm / npm / yarn ## Use a Template Start a Nuxt 4 project with `@movk/nuxt` preconfigured using the [Movk Nuxt Starter](https://github.com/mhaibaraai/movk-nuxt-starter) template. ```bash npm create nuxt@latest -- -t gh:mhaibaraai/movk-nuxt-starter ``` > [!TIP] > See: https://github.com/new?template_name=movk-nuxt-starter&template_owner=mhaibaraai > > You can also click > > Use this template > > on GitHub to create a repository from it. ## Add to a Nuxt Project ### Install Required Dependencies > [!WARNING] > > Movk Nuxt > > depends on > > @nuxt/ui > > and > > zod > > . Make sure they are installed. > [!WARNING] > > If you are using pnpm: > > - Make sure you set `shamefully-hoist=true` in your `.npmrc` file > - Or install `tailwindcss` in the project root directory ```bash [pnpm] pnpm add @movk/nuxt @nuxt/ui zod tailwindcss ``` ```bash [npm] npm install @movk/nuxt @nuxt/ui zod tailwindcss ``` ```bash [yarn] yarn add @movk/nuxt @nuxt/ui zod tailwindcss ``` ### Module Configuration Register the module in `nuxt.config.ts`: ```diff [nuxt.config.ts] export default defineNuxtConfig({ + modules: ['@movk/nuxt'] }) ``` ### Import Styles Import the module styles from your CSS entry, and register that file under `css` in `nuxt.config.ts`: ```css [app/assets/css/main.css] @import "tailwindcss"; @import "@movk/nuxt"; ``` ```diff [nuxt.config.ts] export default defineNuxtConfig({ modules: ['@movk/nuxt'], + css: ['~/assets/css/main.css'] }) ``` > [!NOTE] > > @movk/nuxt > > already imports > > @nuxt/ui > > , so there is no need to > > @import "@nuxt/ui" > > separately. Keep a single Tailwind entry in the project: a second > > @import "tailwindcss" > > creates a second Tailwind context whose default theme variables override the ones the module injects, such as > > --font-sans > > . ### Install the Icon Collection Component icons come from Iconify's `lucide` collection. With the matching `@iconify-json` package installed, the module inlines the icons its components use at build time; without it those icons are fetched from the Iconify API at runtime, which fails on intranets and offline. ```bash [pnpm] pnpm add -D @iconify-json/lucide ``` ```bash [npm] npm install -D @iconify-json/lucide ``` ```bash [yarn] yarn add -D @iconify-json/lucide ``` The module only covers icons used by its own components. Enable scanning so the icon names written in your project are bundled too: ```ts [nuxt.config.ts] export default defineNuxtConfig({ icon: { clientBundle: { scan: { globInclude: ['**/*.{vue,jsx,tsx,ts,md,mdc,mdx,yml,yaml}'] } } } }) ``` > [!NOTE] > > The default > > globInclude > > of > > @nuxt/icon > > excludes > > .ts > > , so icon names declared in composables or constant files are missed — hence the explicit > > ts > > entry above. ## Optional Configuration ```ts [nuxt.config.ts] export default defineNuxtConfig({ modules: ['@movk/nuxt'], movk: { // Component prefix (default: 'M') prefix: 'M' } }) ``` ## TypeScript Support Movk Nuxt provides full TypeScript type definitions that are automatically injected into your project after installation. ```ts import type { z } from 'zod' const { afz } = useAutoForm() const schema = afz.object({ email: afz.email(), // ✅ Full type hints age: afz.number() }) // Infer data type from schema type FormData = z.output ``` ## Zod v4 Integration Movk Nuxt uses **Zod v4**, which introduces some important API changes: ```ts [✅ Correct Usage (Zod v4)] import { z } from 'zod' // Use dedicated validation functions const emailSchema = z.email() const urlSchema = z.url() const uuidSchema = z.uuid() const datetimeSchema = z.iso.datetime() ``` ```ts [❌ Deprecated (Zod v3)] import { z } from 'zod' // Do not use old string validation methods const emailSchema = z.string().email() const urlSchema = z.string().url() const uuidSchema = z.string().uuid() ``` > [!TIP] > See: https://zod.dev/api > > See the official Zod documentation for more v4 changes # Module Configuration > Configure component prefix, theme colors, fonts, API endpoints, auth strategy, response parsing rules and Toast notification behavior. ## Introduction Movk Nuxt uses `movk` as the configuration key in `nuxt.config.ts`: ## `Prefix` - **Type**: `string` - **Default**: `'M'` Component prefix, used to avoid naming conflicts with other component libraries. ```ts [nuxt.config.ts] export default defineNuxtConfig({ movk: { prefix: 'My' // Components become MyAutoForm, MyDatePicker, etc. } }) ``` ## `Theme` The theme module centrally manages colors, radius, icon sets and fonts. The first three provide options to the `ThemePicker` component and `useTheme` composable, while the font is injected at build time. All fields are configured under `movk.theme`. > [!NOTE] > See: /en/docs/getting-started/theme > > Runtime capabilities of the theme system (dynamic switching, CSS export) are documented in the theme docs; for interactive tuning see the > > ThemePicker > > component. ```ts [nuxt.config.ts] export default defineNuxtConfig({ movk: { theme: { enabled: true } } }) ``` **enabled** (`boolean`): Whether to enable the theme module (appConfig defaults, theme plugin, ThemePicker component registration). Defaults to true. When disabled, ThemePicker is no longer registered. **colors** (`string[]`): List of color aliases available to components, passed through to @nuxt/ui's theme.colors. Defaults to ['primary', 'secondary', 'success', 'info', 'warning', 'error']. **defaultVariants** (`object`): Component default variants, passed through to @nuxt/ui's theme.defaultVariants. **prefix** (`string`): Tailwind CSS utility class prefix, passed through to @nuxt/ui's theme.prefix. For example 'tw'. **font** (`string | ThemeFontOption`): Global font. For built-in fonts the name is enough ('Alibaba PuHuiTi', 'OPPO Sans') and the module injects the stylesheet, a preconnect and a --font-sans carrying the Chinese fallback stack at build time; for self-hosted fonts use the { name, href } form to supply the stylesheet URL. When omitted, --font-sans is not injected and the font is controlled entirely by your project's CSS @theme.Font name, which must match the font-family declared by @font-face in the stylesheet character for character.URL of the font's entry CSS. For example '/fonts/my-font.css'. Optional for built-in fonts. A font that is neither built in nor given this field triggers no request at all. **radius** (`number`): Default radius (in rem). When omitted, --ui-radius is not injected and the @nuxt/ui default or your project CSS applies. For example 0.5. **radiuses** (`number[]`): ThemePicker radius options (in rem). Defaults to [0, 0.125, 0.25, 0.375, 0.5]. **neutralColors** (`string[]`): ThemePicker neutral color options. ### Custom Font ```ts [nuxt.config.ts] export default defineNuxtConfig({ movk: { theme: { // Built-in fonts only need the name font: 'Alibaba PuHuiTi' // Self-hosted fonts supply the entry CSS URL // font: { name: 'My Font', href: '/fonts/my-font.css' } } } }) ``` ## `Icon` Controls whether the module's own icons enter the `@nuxt/icon` build-time bundle. ```ts [nuxt.config.ts] export default defineNuxtConfig({ movk: { icon: { clientBundle: true } } }) ``` **clientBundle** (`boolean`): Whether to inject the icons used by movk components and the built-in icon sets into the build-time bundle. Defaults to true. When disabled, those icons are fetched on demand at runtime. > [!NOTE] > See: /en/docs/getting-started/theme > > See Theme · Icon Sets for switching icon sets and installing the > > @iconify-json/* > > packages. ## API The API system provides complete request wrapping and auth management, configured via the `api` option. > [!NOTE] > See: /en/docs/api > > See the API docs for full usage of the API system. ### Basic Configuration ```ts [nuxt.config.ts] export default defineNuxtConfig({ movk: { api: { // Whether to enable API functionality enabled: true, // Default endpoint name defaultEndpoint: 'default', // Whether to enable debug mode debug: false } } }) ``` **enabled** (`boolean`): Whether to enable API functionality. Defaults to true. **defaultEndpoint** (`string`): Default endpoint name. Defaults to 'default'. **debug** (`boolean`): Whether to enable debug mode; when enabled, request logs are printed to the console. Defaults to false. ### `endpoints` Supports configuring multiple API endpoints, each with its own independent configuration: ```ts [nuxt.config.ts] export default defineNuxtConfig({ movk: { api: { endpoints: { // Default endpoint default: { baseURL: '/api' }, // Admin endpoint admin: { baseURL: '/admin-api', auth: { tokenType: 'Bearer' } }, // Third-party API external: { baseURL: 'https://api.example.com', // Injected on the server only headers: { 'X-Secret-Key': process.env.EXTERNAL_SECRET_KEY }, // Injected on both server and client publicHeaders: { 'X-Api-Version': '2' } } } } } }) ``` #### Endpoint Options **baseURL** (`string`) *required*: Base URL of the endpoint. **alias** (`string`): Endpoint alias. **headers** (`Record`): Default request headers for this endpoint. Server-side only; not exposed to the client. **publicHeaders** (`Record`): Public request headers for this endpoint. Stored in the public runtimeConfig and injected on both server and client. Keys of the same name are overridden by headers. Use for non-secret constant headers only. **auth** (`Partial`): Auth configuration for this endpoint, merged with the global config. **toast** (`Partial`): Toast configuration for this endpoint, merged with the global config. **response** (`Partial`): Response configuration for this endpoint, merged with the global config. ### `auth` Configure automatic auth behavior, integrated with `nuxt-auth-utils`: > [!NOTE] > > The module automatically registers `nuxt-auth-utils` when `auth.enabled` is `true` and `tokenSource` is `'session'`. To use `useUserSession` on its own, add `nuxt-auth-utils` to `modules`. > > With `nuxt-auth-utils` v0.6, set `NUXT_APP_SECRET` to a value of at least 32 characters in production. Generate one with `openssl rand -base64 32`. In development, Nuxt generates a secret if the variable is unset. > > When upgrading from v0.5, remove `NUXT_SESSION_PASSWORD` and `runtimeConfig.session.password`. Signed-in users will need to sign in again once after the upgrade. [Migration guide](https://nuxt.com/modules/auth-utils#migrate-from-v05) ```ts [nuxt.config.ts] export default defineNuxtConfig({ movk: { api: { auth: { // Enable auth enabled: true, // Token source tokenSource: 'session', // Path to token in session sessionTokenPath: 'user.accessToken', // Token type tokenType: 'Bearer', // Header name headerName: 'Authorization', // 401 unauthorized handling config unauthorized: { // Redirect to login page on 401 redirect: true, loginPath: '/login', // Clear session on 401 clearSession: true } } } } }) ``` When calling a third-party API directly from the browser, put the credential in `runtimeConfig.public` and point at it: ```ts [nuxt.config.ts] export default defineNuxtConfig({ runtimeConfig: { public: { llmApiKey: '' } }, movk: { api: { auth: { enabled: true, tokenSource: 'public-runtime-config', tokenPath: 'llmApiKey', tokenType: 'Bearer', unauthorized: { redirect: false } } } } }) ``` ```bash [.env] NUXT_PUBLIC_LLM_API_KEY=your-api-key ``` > [!WARNING] > > Values from > > public-runtime-config > > and > > publicHeaders > > are shipped to the browser along with the page, and any visitor can read them. Use them only when the credential is designed to be public, or its scope is narrow enough to accept the exposure. Account-level keys belong behind a server-side proxy. #### Auth Options **enabled** (`boolean`): Whether to enable auth. Defaults to false. **tokenSource** (`'session' | 'public-runtime-config'`): Token source. 'session' retrieves it from the nuxt-auth-utils session; 'public-runtime-config' retrieves it from runtimeConfig.public, for credentials that are meant to be exposed in the browser. Defaults to 'session'. **sessionTokenPath** (`string`): Path to the token in the session. For example 'token' maps to session.token, 'user.token' maps to session.user.token. Defaults to 'token'. **tokenPath** (`string`): Path to the token in runtimeConfig.public, dot-notation supported. Only applies when tokenSource is 'public-runtime-config'. Defaults to 'apiToken'. **tokenType** (`'Bearer' | 'Basic' | 'Custom'`): Token type. Defaults to 'Bearer'. **customTokenType** (`string`): Custom token type value, used when tokenType is 'Custom'. **headerName** (`string`): Header name. Defaults to 'Authorization'. **unauthorized** (`ApiUnauthorizedConfig`): Configuration for handling 401 unauthorized errors.Whether to automatically redirect to the login page on a 401 error. Defaults to true.Login page path. Defaults to '/login'.Whether to automatically clear the session on a 401 error. Defaults to true. ### `response` Configure API response parsing rules, including business status code determination, data unwrapping fields and message extraction: ```ts [nuxt.config.ts] export default defineNuxtConfig({ movk: { api: { response: { // Successful status code list successCodes: [200, 0], // Status code field name codeKey: 'code', // Message field name messageKey: 'message', // Data field name dataKey: 'data', // Whether to validate the business status code businessCheck: true, // Whether to unwrap by dataKey unwrap: true } } } }) ``` An endpoint-level `response` overrides the global one. Endpoints returning a bare array or object turn off checking and unwrapping; explicit per-request `businessCheck` / `unwrap` values can still override: ```ts [nuxt.config.ts] export default defineNuxtConfig({ movk: { api: { endpoints: { sensor: { baseURL: 'https://sensor.example.com', response: { businessCheck: false, unwrap: false } } } } } }) ``` #### Response Configuration Options **successCodes** (`(number | string)[]`): Successful status code list; a code value in the response is considered successful if it is in this list. Defaults to [200, 0]. **codeKey** (`string`): Field name for the status code in the response. Defaults to 'code'. **messageKey** (`string`): Field name for the message in the response. Defaults to 'message'. **dataKey** (`string`): Field name for the data in the response. Defaults to 'data'. **businessCheck** (`boolean`): Whether to validate the business status code against successCodes; when off, any 2xx response is a success. Defaults to true. **unwrap** (`boolean`): Whether to unwrap business data by dataKey; when off, callers receive the raw response body. Defaults to true. ### `toast` Configure global Toast notification behavior: ```ts [nuxt.config.ts] export default defineNuxtConfig({ movk: { api: { toast: { // Enable notifications globally enabled: true, // Success notification config success: { show: true, color: 'success', duration: 3000, // Only notify on mutating requests, stay quiet on GET methods: ['POST', 'PUT', 'PATCH', 'DELETE'] }, // Error notification config error: { show: true, color: 'error', duration: 3000 } } } } }) ``` #### Toast Options **enabled** (`boolean`): Whether to enable notifications globally. Defaults to true. **success** (`Partial & { show?: boolean, methods?: string[] }`): Success notification configuration. show: false disables it; methods restricts it to the listed HTTP methods (case-insensitive), and omitting the field means no restriction. **error** (`Partial & { show?: boolean, methods?: string[] }`): Error notification configuration. show: false disables it; methods works the same way, and is usually left unset so errors surface on every method. > [!NOTE] > > enabled > > , > > show > > and > > methods > > are all global-level switches that a single request can override. Precedence: request-level > > show > > > request-level > > successMessage > > / > > errorMessage > > > global > > success.show > > / > > error.show > > / > > methods > > > global > > enabled > > . So when a toast is globally disabled or the method misses the whitelist, both > > toast: { success: { show: true } } > > and > > toast: { successMessage: 'Saved' } > > still show it. > [!TIP] > > methods > > only belongs in the global or endpoint config — a single request has exactly one method, so request-level > > toast > > does not accept the field. An endpoint-level > > methods > > replaces the global one instead of merging the arrays. ## Configuration Priority Configuration is merged in the following priority order (later overrides earlier): 1. **Module built-in defaults** - Default config defined in `api-defaults.ts` 2. **Global config** - `movk.api.auth`, `movk.api.toast`, `movk.api.response` 3. **Endpoint config** - `movk.api.endpoints[name].auth`, etc. 4. **Request-level config** - `toast` option in `useApiFetch`, etc. ```ts // Example: request-level config overrides global config const { data } = await useApiFetch('/users', { toast: { successMessage: 'Fetched successfully', // Overrides global config error: false // Disable error notifications } }) ``` Request headers are layered in the following order (later overrides earlier): 1. **Endpoint `publicHeaders`** - Injected on both server and client 2. **Endpoint `headers`** - Injected on the server only, overrides matching `publicHeaders` keys 3. **Request-level `headers`** - Passed to `$api` or `useApiFetch` 4. **Auth injection** - Written by the `onRequest` interceptor under `headerName`, highest priority ## Component and Validation Locale Set the locale on `UApp` to change component text. Use `extendMovkLocale(locale, overrides)` to override individual messages and `useMovkLocale()` to read the active locale code and translator. ```ts [nuxt.config.ts] export default defineNuxtConfig({ movk: { zod: { locale: 'auto', fallback: 'en', locales: ['en', 'zh-CN'] } } }) ``` `movk.zod` configures the global validation locale and required messages. With `auto`, AutoForm and SearchForm follow UApp on the client and use `fallback` on the server. Set `customError` through `movk:zod:config` to customize those forms in the current Nuxt application. In Vue + Vite pass `{ zod: { customError } }` to the Vue plugin. Direct Zod validation uses the configured global locale or fallback. ## Environment Variables For sensitive configuration (such as API keys), use environment variables: ```ts [nuxt.config.ts] export default defineNuxtConfig({ movk: { api: { endpoints: { external: { baseURL: process.env.EXTERNAL_API_URL, headers: { 'X-API-Key': process.env.EXTERNAL_API_KEY } } } } } }) ``` ```bash [.env] EXTERNAL_API_URL=https://api.example.com EXTERNAL_API_KEY=your-api-key ``` > [!WARNING] > > Never write sensitive information (such as API keys or passwords) directly in configuration files; always use environment variables. # Vue / Vite > Use Movk standalone components, theming and composables in a plain Vue + Vite project without Nuxt. > [!NOTE] > See: /en/docs/getting-started/installation > > Using > > Nuxt > > ? See the Nuxt mode installation instructions. `@movk/nuxt` is not just a Nuxt module — it also provides a Vite plugin (`@movk/nuxt/vite`) and a Vue plugin (`@movk/nuxt/vue-plugin`), making standalone UI components, AutoForm / DataTable, theming and non-server-side composables available directly in plain Vue + Vite projects. > [!WARNING] > > Vue / Vite mode > > does not include the API integration domain > > ( > > useApiFetch > > / > > useLazyApiFetch > > / > > useClientApiFetch > > , upload/download, > > $api > > plugin, auth and error toasts, etc.) — these depend on the Nuxt server runtime and are only available in Nuxt mode. ## Installation ### Install Dependencies Requires `@nuxt/ui >=4.13.0`. ```bash [pnpm] pnpm add @movk/nuxt @nuxt/ui zod tailwindcss ``` ```bash [npm] npm install @movk/nuxt @nuxt/ui zod tailwindcss ``` ```bash [yarn] yarn add @movk/nuxt @nuxt/ui zod tailwindcss ``` vue-router is enabled by default (controlled via the `ui.router` option). If using the default, also install `vue-router`: ```bash [pnpm] pnpm add vue-router ``` ```bash [npm] npm install vue-router ``` ### Add the Vite Plugin Register the `movk()` plugin in `vite.config.ts`: ```ts [vite.config.ts (Vite)] import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import movk from '@movk/nuxt/vite' export default defineConfig({ plugins: [ vue(), movk() ] }) ``` ```ts [vite.config.ts (Inertia)] import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import movk from '@movk/nuxt/vite' export default defineConfig({ plugins: [ vue(), movk({ ui: { router: 'inertia' } }) ] }) ``` > [!TIP] > > `movk()` internally registers `unplugin-auto-import` and `unplugin-vue-components`, which generate `auto-imports.d.ts` and `components.d.ts`. It is recommended to add them to `.gitignore` and include them in `tsconfig`. > > ```json [tsconfig.app.json] > { > "include": ["src/**/*.ts", "src/**/*.vue", "auto-imports.d.ts", "components.d.ts"] > } > ``` > > ```bash [.gitignore] > auto-imports.d.ts > components.d.ts > ``` > [!TIP] > > If using TypeScript, you can add aliases for theme virtual modules in `tsconfig` for completions in `vite.config.ts`: > > ```json [tsconfig.node.json] > { > "compilerOptions": { > "paths": { > "#build/movk-ui": ["./node_modules/.movk-ui/movk-ui"], > "#build/ui": ["./node_modules/.nuxt-ui/ui"] > } > } > } > ``` ### Register the Vue Plugin Register `@movk/nuxt/vue-plugin` in your entry file (it already links in `@nuxt/ui/vue-plugin` internally): ```ts [src/main.ts] import './assets/css/main.css' import { createApp } from 'vue' import { createRouter, createWebHistory } from 'vue-router' import movk from '@movk/nuxt/vue-plugin' import App from './App.vue' const router = createRouter({ routes: [], history: createWebHistory() }) createApp(App) .use(router) .use(movk) .mount('#app') ``` ### Import Styles ```css [src/assets/css/main.css] @import "tailwindcss"; @import "@movk/nuxt"; ``` ### Wrap the Root Component with `` `` provides the global context for Toast, Tooltip and imperative overlays; `useMessageBox` depends on it: ```vue [src/App.vue] ``` > [!NOTE] > > It is recommended to add > > class="isolate" > > to the root container ( > > #app > > in > > index.html > > ) to ensure proper style scoping and overlay stacking. ## Coexisting with UnoCSS / Existing Global Styles When adding Movk to an existing project, a common problem is that the background, padding, border radius and other styles of Nuxt UI components have no effect. The cause is cascade layers: Tailwind utilities live in `@layer utilities`, and **any unlayered style beats styles inside `@layer`, regardless of selector specificity**. The preflight (reset) that UnoCSS outputs by default and a project's own global reset are both unlayered. > [!TIP] > > In the Styles panel of the browser DevTools, rules without a cascade layer label are unlayered. In dev mode, > > movk() > > prints a warning in the terminal when UnoCSS outputs an unlayered reset. ### Disable the UnoCSS Reset `@import "tailwindcss"` already provides an equivalent reset in `@layer base`, so you can simply disable the UnoCSS reset: ```ts [uno.config.ts] import { defineConfig, presetWind4 } from 'unocss' export default defineConfig({ presets: [ presetWind4({ preflights: { reset: false } }) ] }) ``` > [!WARNING] > > The > > presetWind4 > > switch is > > preflights.reset > > . A top-level > > reset: false > > has no effect. ### Move the UnoCSS Preflight into the Base Layer To keep the UnoCSS preflight, use `outputToCssLayers` to put it in Tailwind's `base` layer while utilities stay unlayered: ```ts [uno.config.ts] export default defineConfig({ outputToCssLayers: { cssLayerName: layer => layer === 'preflights' ? 'base' : null } }) ``` > [!NOTE] > > Do not move UnoCSS utilities into a layer as well. If the project also has unlayered component library styles such as Element Plus, layered utilities lose to them, and existing code that overrides library styles with utilities stops working. ### Move an Existing Global Reset into the Base Layer Wrap the project's own reset in `@layer base` so it no longer overrides Nuxt UI utilities: ```css [src/styles/reset.css] @layer base { *, ::before, ::after { margin: 0; padding: 0; } } ``` ## Options Pass options into `movk()` in `vite.config.ts` for configuration. ### `prefix` Component Prefix Component name prefix. - Default: `M` ```ts [vite.config.ts] movk({ prefix: 'M' }) ``` ### `site` Site Information Site name, affects the localStorage key prefix for theme persistence (`-ui-*`). ```ts [vite.config.ts] movk({ site: { name: 'my-app' } }) ``` ### `theme` Theme `theme.colors` (color aliases), `theme.defaultVariants` (default variants), `theme.prefix` (aligned with the Tailwind prefix), etc. — mirrors the Nuxt mode `movk.theme`. ```ts [vite.config.ts] movk({ theme: { defaultVariants: { color: 'neutral', size: 'sm' } } }) ``` ### `icon` Icons `icon.clientBundle` controls whether the icons used by movk components and the built-in icon sets enter the build-time icon bundle, mirroring the Nuxt mode `movk.icon`. The icon data requires the matching `@iconify-json/*` packages in your project; collections that are not installed are skipped automatically (never a build failure). See [Theme · Icon Sets](https://nuxt.mhaibaraai.me/en/docs/getting-started/theme#icon-sets). ```ts [vite.config.ts] movk({ icon: { clientBundle: false } }) ``` ### `ui` `ui` is a passthrough for `@nuxt/ui` unplugin configuration (`Partial`), hosting `router`, `colorMode`, `autoImport`, `components`, `dts`, `icon`, `ui` theme, etc. Movk automatically injects its own composables, component resolution and icons into `ui.autoImport` / `ui.components` / `ui.icon.clientBundle.icons`, so no manual configuration is needed. > [!NOTE] > See: https://ui.nuxt.com/docs/getting-started/installation/vue#options > > See the Nuxt UI module docs for the full configuration and features of the > > ui > > option. # Theme System > Manage colors, radius, icon sets and dark mode through module defaults, the ThemePicker component and the useTheme composable, with build-time font configuration. ## Introduction Movk Nuxt provides unified runtime theme management on top of [Nuxt UI](https://ui.nuxt.com) theming: colors, radius, fonts, icon sets and dark mode are all centrally controlled and can be interactively adjusted at runtime, with one-click export of CSS variables or configuration code. Theme capabilities consist of three parts: - **[Module defaults](https://nuxt.mhaibaraai.me/en/docs/getting-started/configuration)**: Declare available options in `movk.theme` inside `nuxt.config.ts`. - **`ThemePicker` component**: A user-facing visual control panel with export support. - **`useTheme` composable**: Read and write theme state in scripts, export CSS/config. ## Enable & Disable The theme module is enabled by default. When disabled, `appConfig` defaults, the theme plugin and the `ThemePicker` component are no longer injected: ```ts [nuxt.config.ts] export default defineNuxtConfig({ movk: { theme: { enabled: false } } }) ``` ## ThemePicker Component `ThemePicker` provides visual switching for colors, radius, icon sets and dark mode, and can export the current theme. > [!TIP] > See: #themepicker-reference > > View the complete props, events and usage of ThemePicker. ## useTheme `useTheme` exposes reactive theme state and export methods, suitable for custom theme panels or reading theme values in business logic: ```ts const { color, neutral, radius, icon, mode, exportCSS, exportConfig, resetTheme } = useTheme() // Read/switch theme color.value = 'green' mode.value = 'dark' // Export current theme const css = exportCSS() const config = exportConfig() ``` > [!TIP] > See: #usetheme-reference > > View all state and methods returned by useTheme. ## Fonts The font is build-time configuration and does not switch at runtime. One line is all it takes: ```ts [nuxt.config.ts] export default defineNuxtConfig({ movk: { theme: { font: 'Alibaba PuHuiTi' } } }) ``` At build time the module does three things, all served straight from SSR with no runtime JS involved: - Writes the font stylesheet `` into `` - Adds a `preconnect` with `crossorigin` for cross-origin fonts - Injects `@theme { --font-sans }`, appending a fallback stack that covers the system Chinese fonts on macOS, Windows and Linux Built-in fonts are hosted by [movk-fonts](https://cdn.mhaibaraai.me). The value must match the `font-family` in their `@font-face` declarations character for character: | Value | Stylesheet | | --- | --- | | `Alibaba PuHuiTi` | `https://cdn.mhaibaraai.me/fonts/alibaba-puhuiti.css` | | `OPPO Sans` | `https://cdn.mhaibaraai.me/fonts/oppo-sans.css` | For self-hosted fonts, use the `{ name, href }` form to supply the stylesheet URL: ```ts [nuxt.config.ts] export default defineNuxtConfig({ movk: { theme: { font: { name: 'My Font', href: '/fonts/my-font.css' } } } }) ``` > [!WARNING] > > A wrong > > name > > raises no error — it silently falls back to the system font. CSS family matching is case-insensitive, but > > alibaba-puhuiti > > and > > Alibaba PuHuiTi > > are two different names. A font that is neither built in nor given an > > href > > triggers no request at all, and the module warns during development. The `@theme` injected by the module lands with `@import "@movk/nuxt"`, so any `@theme` written after it overrides `--font-sans`. To control the font entirely from your own CSS, leave `movk.theme.font` unset: ```css [app/assets/css/main.css] @import "tailwindcss"; @import "@movk/nuxt"; @theme { --font-sans: "OPPO Sans", sans-serif; } ``` > [!NOTE] > > Chinese fonts are split by > > unicode-range > > , so the browser only downloads the shards holding characters the page actually uses. That is why these fonts > > must not > > be handed to > > @nuxt/fonts > > — it downloads every shard into the build output at build time, losing both on-demand loading and the CDN cache shared across projects. > > @movk/nuxt > > already sets > > ui.fonts: false > > by default, so your project never needs to declare it. ## Icon Sets `ThemePicker` and `useTheme` switch between the Lucide, Phosphor and Tabler icon sets at runtime. Switching only rewrites `appConfig.ui.icons` — no rebuild required. By default the module feeds the icons used by its own components, plus all three icon sets, into the `@nuxt/icon` build-time bundle, so nothing has to be fetched from the Iconify API at runtime. Each set needs its own `@iconify-json` package to be inlined: ```bash npx nypm add -D @iconify-json/lucide @iconify-json/ph @iconify-json/tabler ``` > [!NOTE] > > A missing collection never fails the build; its icons simply fall back to on-demand runtime loading. The module warns when the default > > lucide > > collection is missing, while > > ph > > and > > tabler > > — only needed after switching icon sets — are reported as a debug log. To opt out entirely (for example when your project manages the icon bundle itself), turn it off; movk component icons then load at runtime: ```ts [nuxt.config.ts] export default defineNuxtConfig({ movk: { icon: { clientBundle: false } } }) ``` ## Radius `--ui-radius` keeps its three-level precedence: `ThemePicker` selection > `movk.theme.radius` > your project CSS. When omitted, the module does not inject the variable and the `@nuxt/ui` default (`0.25rem`) applies, so your project can override it in its own CSS: ```css [app/assets/css/main.css] @theme { --ui-radius: 0.5rem; } ``` ## Customizing Options Color aliases, radius steps and neutral colors can all be overridden in `movk.theme`, serving as the value range for `ThemePicker` and `useTheme`: ```ts [nuxt.config.ts] export default defineNuxtConfig({ movk: { theme: { colors: ['primary', 'secondary', 'success', 'info', 'warning', 'error'], radiuses: [0, 0.125, 0.25, 0.375, 0.5], neutralColors: ['slate', 'gray', 'zinc', 'neutral', 'stone'] } } }) ``` > [!TIP] > See: /en/docs/getting-started/configuration > > See Module Configuration · Theme for field descriptions ## Export & Reuse The CSS variables exported by `ThemePicker` and `useTheme.exportCSS()` can be written directly into your project's `main.css`, solidifying runtime debugging results as the default theme: ```css [app/assets/css/main.css] @import "tailwindcss"; @import "@movk/nuxt"; :root { /* Paste variables exported by exportCSS() */ } ``` ## ThemePicker Reference ### Introduction `MThemePicker` is a visual theme configuration component that allows users to preview and customize the application theme in real time. It unifies adjustments to `primary`, `neutral`, border-radius, icon sets, and color mode, with support for exporting CSS variables and `app.config.ts` configuration code. > [!NOTE] > See: https://github.com/nuxt/ui/tree/v4/docs/app/components/theme-picker > > Configuration changes are stored locally and automatically restored on the next visit. The component source originates from Nuxt UI. > [!NOTE] > > MThemePicker > > is part of the theme module. If > > movk.theme.enabled > > is set to > > false > > , this component will not be registered. ### Usage `MThemePicker` is typically used as a global theme configuration entry, placed in the application header or toolbar: > [!TIP] > > The current theme tokens update immediately after panel operations, making it easy to verify configuration changes. Use > > useTheme > > to read reactive state: ```vue [ComponentsThemePickerStateExample.vue] ``` ### Features #### Primary Color Configuration - **Primary**: Choose the main brand color, supporting black or preset colors - **Neutral**: Configure neutral tones affecting text and backgrounds #### Style Configuration - **Radius**: Adjust global border-radius size (0–5 levels) - **Icons**: Switch icon sets (Lucide, Phosphor, Tabler) #### Color Mode Three color modes are supported: - `light`: Light mode - `dark`: Dark mode - `system`: Follow system preference #### Export Configuration Once configured, you can export: - `main.css`: CSS variable configuration - `app.config.ts`: Application configuration code ### Theme ::component-theme :: ### Changelog See commit history for [src/runtime/components/theme-picker/Theme System.vue](https://github.com/mhaibaraai/movk-nuxt/commits/main/src/runtime/components/theme-picker/Theme System.vue). ## useTheme Reference ### Introduction `useTheme` exposes the reactive theme state and export methods. It is the underlying logic for the [`ThemePicker`](#themepicker-reference) component and can be used to build custom theme panels or read/write theme values in business logic. ### Return Values ```ts const { // Color color, primary, primaryColors, neutral, neutralColors, blackAsPrimary, setBlackAsPrimary, // Radius / Icon / Mode radius, radiuses, icon, icons, mode, modes, // Injection and state style, hasCSSChanges, hasConfigChanges, // Export exportCSS, exportConfig, resetTheme } = useTheme() ``` | Group | Members | Description | | --- | --- | --- | | Color | `color` / `primary` / `primaryColors` | Primary color and available options | | Color | `neutral` / `neutralColors` | Neutral color and available options | | Color | `blackAsPrimary` / `setBlackAsPrimary` | Toggle for using black as the primary color | | Radius | `radius` / `radiuses` | Current border radius and available presets | | Icon | `icon` / `icons` | Current icon set and available options | | Mode | `mode` / `modes` | Dark mode (`light`/`dark`/`system`) and available options | | Injection | `style` | CSS variables to inject into the page | | State | `hasCSSChanges` / `hasConfigChanges` | Whether there are changes relative to the defaults | > [!TIP] > See: #themepicker-reference > > For a ready-to-use visual theme panel, see the ThemePicker component. # Migrate to v2 > Breaking changes to handle when upgrading from v1 to v2. ## Overview v2 refocuses on schema-driven admin features (AutoForm, SearchForm, DataTable and API) and removes components that overlap with Nuxt UI or offer little reuse value. This guide covers the behavior changes and replacements to check during the upgrade. ## Upgrade Steps 1. **Check runtime requirements.** Verify the supported versions, then update dependencies and the lockfile. See [Runtime and API](#runtime-and-api). 2. **Replace removed features.** Check the [component and type replacements](#removed-components) and [AutoForm controls](#removed-autoform-control-types). 3. **Review behavior changes.** Check [Forms, Table and Locale](#forms-table-and-locale) and the [API migration table](https://nuxt.mhaibaraai.me/en/docs/api#migrating-from-v1-to-v2). 4. **Verify the migration.** Run the project's lint, type checks, tests and build, then check the workflows your project uses. ## Migrate with AI Open your coding assistant in the project root, then expand and copy the prompt or ask the assistant to read [the Markdown version of this page](https://nuxt.mhaibaraai.me/raw/en/docs/getting-started/migration.md). The prompt uses `v1.8.3` as its baseline and asks the assistant to check for earlier v1 changes when they apply. ```text Upgrade this project from @movk/nuxt v1 to v2. Preserve its business workflows, data formats and interactions. Start with the project instructions, package.json, lockfile, Nuxt or Vite configuration, app.config, app entry point and CI configuration. Identify the installed v1 version, the target v2 version, the package manager and whether the project uses Nuxt or Vue + Vite. Verify this checklist against the target version's source, type declarations and migration guide. If the project predates v1.8.3, also check changes between the installed version and v1.8.3. List affected files and the expected changes for each applicable item, then update the features the project uses. References - Movk Nuxt migration guide https://nuxt.mhaibaraai.me/en/docs/getting-started/migration - Documentation index https://nuxt.mhaibaraai.me/llms.txt - API migration table https://nuxt.mhaibaraai.me/en/docs/api#migrating-from-v1-to-v2 - Nuxt Auth Utils migration guide https://nuxt.com/modules/auth-utils#migrate-from-v05 - Nuxt Site Config v5 changes https://github.com/harlan-zw/nuxt-site-config/releases/tag/v5.0.0 Migration checklist 1. Runtime and dependencies - Align Node.js in development, CI and deployment with ^22.22.3 || ^24.15.0 || >=26.0.0. Nuxt mode requires Nuxt ^4.6.4. Use compatible Nuxt UI 4 (4.13.0 or later) and Zod 4 (4.3.6 or later). Update dependencies and the lockfile with the project's package manager. - In Vue + Vite projects, check @movk/nuxt/vite, virtual:movk-plugins and the CSS entry. API integration, file transfers and streaming require Nuxt. Keep a single Tailwind CSS entry with @import "@movk/nuxt". - If the project pins reka-ui directly, align it with the target Nuxt UI version. If it directly uses nuxt-site-config, tailwind-variants or related modules, check major-version changes to configuration and types. Movk Nuxt removed maska and colortranslator, so keep them as direct dependencies if project code uses them. 2. Removed components, types and themes - Search templates, imports, component types and theme configuration using the project's component prefix. Replace WithClear, WithCopy, WithPasswordToggle, WithCharacterLimit, WithFloatingLabel and AsPhoneNumberInput by composing Nuxt UI input components. - Replace PillGroup with URadioGroup, UCheckboxGroup, UToggleGroup or UTabs according to whether it selects one value, selects multiple values or switches panels. Compose UColorPicker with UPopover for ColorChooser. Use UPopover or useMessageBox().confirm for Popconfirm. Provide a replacement for SlideVerify that preserves the verification workflow. - Check v-model bindings, events, slots, accessibility and styling in replacement wrappers. Remove legacy component type imports and theme entries. 3. AutoForm and SearchForm - Find withClear, withCopy, withPasswordToggle, withCharacterLimit, withFloatingLabel, asPhoneNumberInput, colorChooser, slideVerify and pillGroup in schemas. Use existing controls and controlProps for simple cases. Register custom controls with defineControl and pass them via controls when you need to preserve enhanced interactions. - Replace AutoForm's :state with v-model, type the bound state with z.input, and check submit handlers against the schema's output type. reset() restores the baseline plus schema defaults. clear() retains only the defaults. Both update the bound object in place, and AutoForm emits a state snapshot. Call setBaseline() after loading an existing record to set the reset target. - Check how conditional rendering affects nested objects, layout fields, validation and submitted values. Fields hidden by meta.if are excluded from validation. hiddenValue controls whether their values are cleared from the model, with field settings taking precedence. Review validation and submit handlers that rely on hidden fields. - Use v-model:expanded to control SearchForm expansion, or defaultExpanded for the initial state. Submission trims strings and drops empty strings, null and undefined while preserving 0 and false. Use :transform-payload="false" or supply a custom function when the raw values matter. Review the complete schema field set emitted by reset/clear, including cleared values represented as undefined, especially when merging filters into an existing object. SearchForm renders supported leaf fields and skips object, array and layout fields. - Adopt asyncItems, array item moves and duplication, toggle / toggleGroup, and isDirty / dirtyFields where needed. With syncQuery in Nuxt or Vue Router, verify initial restore, back and forward navigation, list refresh on query-restore, and whether updates replace or add history entries. 4. DataTable and Tree - Replace confirmText / cancelText / confirmButtonProps / cancelButtonProps in table action confirmations with confirmLabel / cancelLabel / confirmButton / cancelButton. Rewrite paginationUi.text as complete templates using empty, total, range, rangeUnknown, selected and pageSize. Check the pagination docs for placeholders. - Verify client and server pagination, tree expansion, row selection and infinite scrolling. For key arrays that control selection, expansion and column visibility, check the relevant v-model bindings and initial values. Check the skeleton shown when an empty table loads. Set skeletonRows: 0 for UTable's default loading style. A supplied loading slot takes precedence. - Adopt columnSettings, persistKey and CSV export where needed. exportCsv only processes data supplied to the table. To export all matching records with server pagination, use exportServerCsv and serverCsvExport with the page's external filters. - Verify Tree's parent-child selection, disabled nodes, selection and expansion before and after searching, and retries after lazy loading fails. Use the leaf strategy, searchMethod / searchDebounce, reload(), getNode(), loadError and searchError where needed. 5. Locale, dates and themes - AutoForm, SearchForm, DataTable, Tree, DatePicker and MessageBox use the UApp locale with an English fallback. Set to retain Chinese text. Use extendMovkLocale or existing component props to customize text. - Enable movk.zod validation localization where needed. locale: 'auto' follows UApp on the client and uses fallback on the server. The customError set by movk:zod:config applies only to AutoForm and SearchForm in the current app. In Vue + Vite, configure zod.customError through the Vue plugin options. Check direct Zod calls and custom error maps. - Without an explicit locale, useDateFormatter uses the UApp locale and falls back to en outside components. Verify that toDate preserves hours, minutes and seconds for values with a time, and that convertData preserves native Date objects and class instances. Use v-model:open to control DatePicker popovers. popoverProps.defaultOpen initializes uncontrolled state. Check open() / close(), negative time zones, month and year displays, field size and disabled state. - Check custom theme prefixes, neutral palettes and initial colors under SSR. If your project uses a custom component prefix, also verify imperative calls through useMessageBox. 6. API, authentication and file transfers (Nuxt) - Find $api (including .use, .raw and .stream), useApiFetch and its variants, uploads, downloads, chat transport and movk:api:* hooks. Replace skipBusinessCheck / skipUnwrap with the inverse businessCheck / unwrap flags. Omitted options inherit the endpoint and global configuration. Move these options and toast from $api context to the top level of the request options. - Business-code validation and dataKey unwrapping are independent. For endpoints returning a bare array or object, set businessCheck: false and unwrap: false in endpoints..response. Override endpoint defaults per request where needed. Custom onRequest / onResponse handlers run after built-in hooks. Set unwrap: false when a handler needs the raw response body. - Check ApiError.data?.kind for business, http, network, timeout or aborted, and read data.code and data.response where needed. Update code that uses FetchError, isBusinessError, error.response or treats error.data as the response body. movk:api:error takes (context, error) and reports at most once after retries finish. User-initiated cancellation skips error reporting. Verify 401s, toasts, retries and SSR authentication. - Rename upload timeoutMs to timeout. Uploads and downloads inherit endpoint publicHeaders and request hooks. Injected authorization headers take precedence over ordinary headers. Disabling business-code validation alone still unwraps the response. Check download progress when Content-Length is absent, JSON error responses and cancellation. SSE and chat transport read streams, and JSON errors follow the endpoint policy. - For nuxt-auth-utils sessions upgrading from v0.5 to v0.6, follow the upstream guide for session configuration, server helpers and deployment. Set NUXT_APP_SECRET in production, remove NUXT_SESSION_PASSWORD and runtimeConfig.session.password, and plan for users to sign in again. Report required environment variable names and keep secret values in the deployment environment. 7. Documentation and AI integration - Update Movk Nuxt doc links in the project. Former composable pages are grouped by feature, SearchForm is under AutoForm, file transfers and streaming are under API, and MCP, llms.txt and Skills are under AI Integration. Run the project's existing lint, type checks, tests and build. Recheck affected workflows such as form submission, pagination, authentication or file transfers. Report changed files, verification results, manual deployment steps and anything you could not verify. ``` ## Removed Components | Component | Replacement | | --- | --- | | `MWithClear` | Compose `UInput`, see the [Nuxt UI Input example](https://ui.nuxt.com/docs/components/input#with-clear-button) | | `MWithCopy` | Compose `UInput`, see the [Nuxt UI Input example](https://ui.nuxt.com/docs/components/input#with-copy-button) | | `MWithPasswordToggle` | Compose `UInput`, see the [Nuxt UI Input example](https://ui.nuxt.com/docs/components/input#with-password-toggle) | | `MWithCharacterLimit` | Compose `UInput`, see the [Nuxt UI Input example](https://ui.nuxt.com/docs/components/input#with-character-limit) | | `MWithFloatingLabel` | Compose `UInput`, see the [Nuxt UI Input example](https://ui.nuxt.com/docs/components/input#with-floating-label) | | `MAsPhoneNumberInput` | Compose `UInput`, see the [Nuxt UI Input example](https://ui.nuxt.com/docs/components/input#as-a-phone-number-input) | | `MPillGroup` | Choose `URadioGroup` / `UCheckboxGroup` with `variant="card"`, `UToggleGroup` or `UTabs` according to the interaction | | `MColorChooser` | `UColorPicker` inside a `UPopover` | | `MSlideVerify` | No built-in replacement; implement your own or use a third-party human verification service | | `MPopconfirm` | Confirm buttons inside a `UPopover`, or the imperative [`useMessageBox`](https://nuxt.mhaibaraai.me/en/docs/components/message-box#usemessagebox) | The `maska` and `colortranslator` dependencies are removed as well, along with the Props / Emits / Slots type exports of these components (such as `WithClearProps`, `PillGroupProps` and `ColorChooserProps`). ## Removed AutoForm Control Types The following `type` values are no longer built in. Using them renders a `[AutoForm] No control mapped` notice: - `withClear`, `withPasswordToggle`, `withCopy`, `withCharacterLimit`, `withFloatingLabel`, `asPhoneNumberInput` - `colorChooser`, `slideVerify`, `pillGroup` For simple cases, configure existing controls through `controlProps`. To retain an enhanced input, wrap it in a project component, register it with `defineControl` and pass `controls` to the form. A custom control can keep its original `type` name. ```ts [Use built-in controls] const schema = afz.object({ // Before: afz.string({ type: 'withPasswordToggle' }) password: afz.string({ controlProps: { type: 'password' } }), // Before: afz.enum([...], { type: 'pillGroup' }) category: afz.enum(['All', 'Frontend', 'Backend'], { type: 'radioGroup', controlProps: { orientation: 'horizontal' } }) }) ``` ```ts [Register a custom control] import PasswordInput from '~/components/PasswordInput.vue' const { afz, controls } = useAutoForm({ withPasswordToggle: defineControl({ component: PasswordInput, controlProps: { class: 'w-full' } }) }) ``` See [Controls](https://nuxt.mhaibaraai.me/en/docs/auto-form/controls#custom-controls) for details. ## Runtime and API | Dependency | Required version | | --- | --- | | Node.js | `^22.22.3 \|\| ^24.15.0 \|\| >=26.0.0` | | Nuxt (Nuxt mode) | `^4.6.4` | | Nuxt UI | `4.13.0` or a later compatible v4 version | | Zod | `4.3.6` or a later compatible v4 version | > [!NOTE] > See: /en/docs/api#migrating-from-v1-to-v2 > > See the API migration table for changes to request options, error handling, hooks and transfer timeouts in Nuxt mode. For a standalone Vue project, check the [Vue / Vite setup](https://nuxt.mhaibaraai.me/en/docs/getting-started/vue). ## Forms, Table and Locale - **AutoForm binding.** Bind input state with `v-model` and type it with `z.input`. The old `:state` still works and emits a development deprecation warning. - **Reset and clear.** `reset()` restores the baseline plus schema defaults. `clear()` keeps only schema defaults. Both update the bound object in place and emit a snapshot. Call `setBaseline()` after loading a record to make it the reset target. - **SearchForm.** Bind expansion with `v-model:expanded`. Submit payloads trim strings and drop empty values by default. Set `:transform-payload="false"` to keep the original payload. - **DataTable.** Action confirmations use `confirmLabel`, `cancelLabel`, `confirmButton` and `cancelButton`. Pagination uses complete templates with the keys `empty`, `total`, `range`, `rangeUnknown`, `selected` and `pageSize`. - **Locale.** Component text and `useDateFormatter` follow the UApp locale with an English fallback. Set the UApp locale or pass a formatter locale when needed. - **DatePicker.** `v-model:open` takes precedence over `popoverProps.open`. `popoverProps.defaultOpen` initializes uncontrolled state. Migrate existing controlled state to `v-model:open` before calling `open()` or `close()`. ## Documentation Paths The docs are reorganized by capability. Old links redirect automatically: - `/docs/composables/*` is split into the matching sections: `useAutoForm` → Forms, `useTheme` → Theme, `useMessageBox` / `useDateFormatter` → their component pages, upload/download and streaming → API - The AutoForm field type pages are merged into [Field Types](https://nuxt.mhaibaraai.me/en/docs/auto-form/field-types), and `SearchForm` moves into the Forms section - The three AI integration pages are merged into [AI Integration](https://nuxt.mhaibaraai.me/en/docs/getting-started/ai) # AI Integration > Help AI assistants understand Movk Nuxt through MCP, llms.txt and Skills. ## MCP Server ### What is MCP? MCP (Model Context Protocol) is a standardized protocol that enables AI assistants to access external data sources and tools. Movk Nuxt provides an MCP server so AI tools can directly access component information, API documentation and usage examples. ### Available Resources The MCP server provides the following resources for AI discovery and browsing: | Resource URI | Description | | --- | --- | | `resource://docs/components` | Complete component list with metadata and category information | | `resource://docs/composables` | Complete composable list with metadata and category information | | `resource://movk-nuxt/auto-form` | Full AutoForm system documentation including configuration, API, field definitions and customization options | | `resource://movk-nuxt/data-table` | Full DataTable system documentation including column configuration, tree data, pagination and style customization | | `resource://movk-nuxt/api` | Full API system documentation including plugin configuration, Hooks, Composables and progress upload/download | | `resource://docs/documentation-pages` | Complete list of all available documentation pages | | `resource://docs/examples` | Complete list of all available example code and demos | Use `@` in tools like Claude Code to access these resources. ### Available Tools #### List Queries | Tool Name | Description | | --- | --- | | `list-components` | List all Movk Nuxt components with their categories and basic information | | `list-examples` | List all available examples on the documentation site | | `list-api` | List API system documentation covering plugins, Hooks and Composables | | `list-data-table` | List all DataTable system documentation | #### Detail Retrieval | Tool Name | Description | | --- | --- | | `get-documentation-page` | Get the full content of a specific documentation page. Supports the `headings` parameter (array of h2 headings, e.g. `["Usage", "API"]`) to reduce response size | | `get-example` | Get an example's implementation code; requires the `exampleName` parameter (PascalCase) | | `get-component` | Get the full API documentation and usage instructions for a specified component | | `get-component-metadata` | Get structured metadata for a specified component (props, slots, emits, etc.) | #### Search & Filter | Tool Name | Description | | --- | --- | | `search-documentation` | Search by title, path, description, or documentation section | | `search-composables` | Search composables by keyword | | `search-icons` | Search available icons | | `search-components-by-category` | Search components by category or keyword | | `search-auto-form-by-category` | Search AutoForm documentation by keyword | | `search-data-table-by-category` | Search DataTable documentation by category or keyword | | `search-api-by-category` | Search API system documentation by category or keyword | > [!TIP] > > For large documentation pages, AI can use the > > headings > > parameter of > > get-documentation-page > > to fetch only the relevant sections (e.g. "Usage" or "API"), reducing response size and improving performance. ### Available Prompts The MCP server provides guided prompts for common workflows: | Prompt Name | Description | | --- | --- | | `find-component-for-usecase` | Recommend the most suitable component for a given use case | | `find-autoform-solution` | Recommend field types and configuration approaches based on form requirements | | `implement-component-with-props` | Provide implementation guidance for a component with specified props | Use `/` in tools like Claude Code to access these prompts. ### Configuration The Movk Nuxt MCP server uses HTTP transport and can be configured in different AI assistants. #### ChatGPT > [!NOTE] > > Using custom connectors for MCP functionality requires a ChatGPT Pro or Plus account, available on the web only. Configure Movk Nuxt as a ChatGPT connector: 1. Enable developer mode: go to "Settings" > "Connectors" > "Advanced settings" > "Developer mode" 2. Open ChatGPT Settings 3. Create a new connector in the Connectors tab: - Name: `Movk Nuxt` - MCP server URL: `https://nuxt.mhaibaraai.me/mcp` - Authentication: `None` 4. Click Create In subsequent conversations, you can invoke the connector from the "Developer mode" tools list in the editor. #### Claude Code > [!NOTE] > > Ensure Claude Code is installed. See the > > Anthropic documentation > > for installation instructions. Add the server via CLI: ```bash claude mcp add --transport http movk-nuxt https://nuxt.mhaibaraai.me/mcp ``` #### Claude Desktop 1. Open Claude Desktop and go to "Settings" > "Developer" 2. Click "Edit Config" to open the local Claude configuration directory 3. Edit `claude_desktop_config.json`: ```json [claude_desktop_config.json] { "mcpServers": { "movk-nuxt": { "command": "npx", "args": [ "mcp-remote", "https://nuxt.mhaibaraai.me/mcp" ] } } } ``` 4. Restart Claude Desktop — the Movk Nuxt MCP server will be registered #### Cursor ##### One-Click Install Click the button below to install the Movk Nuxt MCP server directly in Cursor: ::install-button{url="https://nuxt.mhaibaraai.me/mcp"} :: ##### Manual Configuration 1. Open Cursor and go to "Settings" > "Tools & MCP" 2. Add the Movk Nuxt MCP server configuration Or create/edit `.cursor/mcp.json` in your project root: ```json [.cursor/mcp.json] { "mcpServers": { "movk-nuxt": { "type": "http", "url": "https://nuxt.mhaibaraai.me/mcp" } } } ``` #### Google Antigravity 1. Open the MCP store from the "..." dropdown in the Agent panel at the top of the editor 2. Click "Manage MCP Servers" 3. Click "View raw config" 4. Edit `mcp_config.json`: ```json [mcp_config.json] { "mcpServers": { "movk-nuxt": { "serverUrl": "https://nuxt.mhaibaraai.me/mcp" } } } ``` 5. Return to "Manage MCP Servers" and click "Refresh" — the Movk Nuxt MCP server will appear in the list #### Gemini CLI 1. Locate the Gemini CLI configuration file (usually at `~/.gemini/settings.json` or the path specified by an environment variable) 2. Append the configuration to the `mcpServers` object: ```json [~/.gemini/settings.json] { "mcpServers": { "movk-nuxt": { "url": "https://nuxt.mhaibaraai.me/mcp" } } } ``` 3. Restart the terminal or reload the CLI — Movk Nuxt MCP tools are now available #### Le Chat Mistral 1. Go to "Intelligence" > "Connectors" 2. Click "Add Connector" and select "Custom MCP Connector" 3. Create a custom MCP connector: - Connector Name: `MovkNuxt` - Connector Server: `https://nuxt.mhaibaraai.me/mcp` #### Visual Studio Code ::install-button{url="https://nuxt.mhaibaraai.me/mcp" ide="vscode"} :: > [!NOTE] > > Requires the > > GitHub Copilot > > and > > GitHub Copilot Chat > > extensions. 1. Open the VS Code Command Palette (Ctrl/Cmd + Shift + P) 2. Type "Preferences: Open Workspace Settings (JSON)" and execute 3. Create or edit `mcp.json` in your project's `.vscode` directory: ```json [.vscode/mcp.json] { "servers": { "movk-nuxt": { "type": "http", "url": "https://nuxt.mhaibaraai.me/mcp" } } } ``` #### Windsurf 1. Go to "Settings" > "Windsurf Settings" > "Cascade" 2. Click "Manage MCPs" > "View raw config" 3. Add the following configuration: ```json [.codeium/windsurf/mcp_config.json] { "mcpServers": { "movk-nuxt": { "type": "http", "url": "https://nuxt.mhaibaraai.me/mcp" } } } ``` #### Zed 1. Go to "Settings" > "Open Settings" 2. Open the JSON settings file 3. Add the context server configuration: ```json [.config/zed/settings.json] { "context_servers": { "movk-nuxt": { "source": "custom", "command": "npx", "args": ["mcp-remote", "https://nuxt.mhaibaraai.me/mcp"], "env": {} } } } ``` #### Opencode 1. Create `opencode.json` in your project root 2. Add the following configuration: ```json [opencode.json] { "$schema": "https://opencode.ai/config.json", "mcp": { "movk-nuxt": { "type": "remote", "url": "https://nuxt.mhaibaraai.me/mcp", "enabled": true } } } ``` #### GitHub Copilot Agent > [!NOTE] > > Repository admin permissions are required to configure MCP servers for the GitHub Copilot coding agent. If you have already completed configuration in VS Code, you can adapt the same structure (replacing the `servers` key with `mcpServers`) and explicitly declare `tools` to list available tools. 1. Open your GitHub repository 2. Go to "Settings" > "Code & automation" > "Copilot" > "Coding agent" 3. Add the following under "MCP configuration": ```json { "mcpServers": { "movk-nuxt": { "type": "http", "url": "https://nuxt.mhaibaraai.me/mcp", "tools": ["*"] } } } ``` 4. Click Save For more information see [Extend coding agent with MCP](https://docs.github.com/en/copilot/how-tos/use-copilot-agents/coding-agent/extend-coding-agent-with-mcp). ### Usage Examples Once configured, you can ask AI assistants questions across Movk Nuxt's four capability domains: **AutoForm (Schema-Driven Forms)** - "How do I automatically generate a form from a Zod schema?" - "What field types are supported? How do I register custom controls?" - "How do I implement conditional field rendering and cross-field dependencies?" - "I want to build a user registration form — how should I organize the schema?" **DataTable (Data Table)** - "What fields does a DataTable column definition have? How do I use a functional column?" - "How do I implement tree data, column pinning and column resizing?" - "How do I configure pagination, load-more and empty states?" - "I need an editable table with a row right-click menu — which APIs should I use?" **API System (Fetch & Progress)** - "What is the difference between `useApiFetch` and `$fetch`?" - "How do I configure multiple endpoints and automatic auth?" - "How do I monitor file upload/download progress?" - "How do I integrate business status codes and Toast notifications?" **Standalone Components & Composables** - "What standalone UI components are available?" - "What props do DatePicker, Tree and MessageBox accept?" - "How do I use `useDateFormatter`, `useTheme` and `useMessageBox`?" - "I need a date range picker — which component is recommended?" AI assistants can use MCP tools to look up documentation and examples. In clients that support MCP prompts, you can also select a guided prompt. ## LLMs.txt ### What is LLMs.txt? LLMs.txt is a structured documentation format designed specifically for large language models (LLMs). Movk Nuxt provides an LLMs.txt file containing complete information about the Nuxt module, enabling AI tools to better understand and assist with Movk Nuxt development. These files are optimized for AI consumption and contain structured information about component APIs, composable signatures, Schema definitions, usage patterns and best practices. ### Available Endpoints We provide LLMs.txt endpoints to help AI tools access our documentation: - `/llms.txt` - A structured overview of all components and composables with links to their documentation (approximately 5K tokens) - `/llms-full.txt` - Full documentation including implementation details, examples, type definitions and best practices (100K+ tokens) ### Choosing the Right File > [!NOTE] > > Most users should start with /llms.txt > > — it contains all the essential information and fits within standard LLM context windows. Only use > > /llms-full.txt > > if you need complete implementation examples and your AI tool supports large contexts (200K+ tokens). ### Important Usage Notes > [!WARNING] > > The @ symbol must be typed manually > > — when using tools like Cursor or Windsurf, you must manually type the > > @ > > symbol in the chat interface. Copying and pasting will break the tool's ability to recognize it as a context reference. ### Using with AI Tools Any AI tool that supports LLMs.txt can use these endpoints to better understand Movk Nuxt. - "Use the Movk Nuxt docs [https://nuxt.mhaibaraai.me/llms.txt](https://nuxt.mhaibaraai.me/llms.txt)" - "Follow the Movk Nuxt complete guide [https://nuxt.mhaibaraai.me/llms-full.txt](https://nuxt.mhaibaraai.me/llms-full.txt)" ## Agent Skills `movk-nuxt` is a usage guide following the [Agent Skills specification](https://agentskills.io/specification). Its entry point, `SKILL.md`, explains how to choose between Nuxt and Vue + Vite. The agent loads the reference files that match the task. | Task | Reference topics | | --- | --- | | Build an editor or filter bar | Zod v4, AutoForm, custom controls, SearchForm, and URL query sync | | Build a data grid | Columns and row actions, tree rows, pagination, infinite scrolling, and CSV export | | Connect a Nuxt app to a backend | API endpoints and auth, `useApiFetch`, transfer progress, SSE, and AI SDK chat transport | | Choose UI components | DatePicker, Tree, MessageBox, and ThemePicker | | Use composables | Date formatting, confirmation dialogs, theme settings, and localization | ### Install Run the [Skills CLI](https://skills.sh) from the project where you want to use the skill. ```bash npx skills add https://nuxt.mhaibaraai.me --skill movk-nuxt ``` You can also install directly from GitHub. ```bash npx skills add https://github.com/mhaibaraai/movk-nuxt/tree/main/docs/skills/movk-nuxt --skill movk-nuxt ``` By default, the skill is installed in the current project. Add `--agent codex` or `--agent claude-code` to target a client, or add `--global` to make it available across projects. #### Quick install in Cursor [Install Skill](cursor://anysphere.cursor-deeplink/install-skill?url=https://github.com/mhaibaraai/movk-nuxt/tree/main/docs/skills/movk-nuxt) ### Use Mention `movk-nuxt` in agent chat and describe the task, for example, “Build a Movk Nuxt search form that keeps its filters in the URL.” Manual invocation varies by client. In Claude Code, type `/movk-nuxt`. You can also configure the [MCP Server](#mcp-server) so the agent can look up component props, events, and examples while using the skill. The documentation site publishes a [skill index](https://nuxt.mhaibaraai.me/.well-known/skills/index.json), and you can browse the [full skill directory](https://github.com/mhaibaraai/movk-nuxt/tree/main/docs/skills/movk-nuxt) on GitHub. # Quickstart > Learn the core design philosophy and basic usage of AutoForm. ## What is AutoForm AutoForm is an automatic form generation system based on Zod Schema. Through declarative Schema definitions, it automatically generates a complete form interface including input controls, validation rules, and layout structure. > [!NOTE] > > **Core Advantages** > > - **Schema is the Form** - A single Schema defines data structure, validation rules, and UI configuration simultaneously > - **Type Safe** - Full TypeScript type inference, from Schema to form data > - **Zero Template Code** - No need to write `v-for` or repetitive form field templates ## Basic Example Create a simple user registration form: ```vue [AutoFormBasicExample.vue] ``` ## API ### Props ```ts /** * Props for the MAutoForm component */ interface MAutoFormProps { /** * Zod 对象 schema,定义表单字段 */ schema: S; /** * 表单状态对象,原地修改。 */ state?: N extends false ? FormState : never | undefined; /** * 外部 loading 状态,与 `loadingAuto` 的提交中状态合并 */ loading?: boolean | undefined; /** * 是否显示默认提交按钮 * @default true */ submit?: boolean | undefined; /** * 提交按钮属性 */ submitButtonProps?: ButtonProps | undefined; /** * 数组字段添加按钮属性 */ addButtonProps?: ButtonProps | undefined; /** * 自定义控件映射 */ controls?: AutoFormControls | undefined; /** * 全局字段元数据配置 */ globalMeta?: ZodAutoFormFieldMeta | undefined; /** * 是否启用自动 loading 功能。 * @default true */ loadingAuto?: boolean | undefined; /** * 表单验证时机,详见 UForm 的 validateOn 属性 * @default [] */ validateOn?: FormInputEvents[] | undefined; /** * 字段被 `meta.if` 隐藏时如何处理其值:`keep` 保留,`clear` 置为 `undefined`;字段 meta 的 `hiddenValue` 优先。 * 无论哪种策略,隐藏字段都不参与校验,也不出现在提交数据中 * @default 'keep' */ hiddenValue?: "clear" | "keep" | undefined; /** * 提交回调;返回 Promise 时配合 `loadingAuto` 显示加载状态 */ onSubmit?: (): void | (event: FormSubmitEvent>): void | undefined; ui?: Record & { root?: SlotClass; base?: SlotClass; collapsible?: SlotClass; header?: SlotClass; footer?: SlotClass; actions?: SlotClass; } | undefined; id?: string | number | undefined; /** * Custom validation function to validate the form state. */ validate?: (state: Partial>): FormError[] | Promise[]> | undefined; /** * Disable all inputs inside the form. */ disabled?: boolean | undefined; /** * The `name` attribute of the form element. * For nested forms (`nested` is true), this is also used as the path of the form's state within its parent form. */ name?: string | undefined; /** * Delay in milliseconds before validating the form on input events. * @default `300` */ validateOnInputDelay?: number | undefined; /** * If true, applies schema transformations on submit. * @default `true` */ transform?: T | undefined; /** * If true, this form will attach to its parent Form and validate at the same time. * @default `false` */ nested?: N | undefined; acceptcharset?: string | undefined; action?: string | undefined; autocomplete?: string | undefined; enctype?: string | undefined; method?: string | undefined; novalidate?: false | true | "true" | "false" | undefined; target?: string | undefined; modelValue?: AutoFormStateType | undefined; } ``` ### Slots ```ts /** * Slots for the MAutoForm component */ interface MAutoFormSlots { header(): any; footer(): any; submit(): any; field-label(): any; field-hint(): any; field-description(): any; field-help(): any; field-error(): any; field-default(): any; } ``` > [!NOTE] > > In addition to component-level slots, AutoForm also supports field-level dynamic slots with full TypeScript type inference and editor autocompletion. > > | Slot Pattern | Example | Description | > | --- | --- | --- | > | `field-{slotType}` | `field-label`, `field-default` | Generic slot, applies to all fields | > | `field-{slotType}:{fieldKey}` | `field-label:username`, `field-default:email` | Specific field slot with **full type inference** | > | `field-{position}:{fieldKey}` | `field-before:profile`, `field-content:tasks` | Nested field layout slot | ### Emits ```ts /** * Emitted events for the MAutoForm component */ interface MAutoFormEmits { error: (payload: [FormErrorEvent]) => void; reset: (payload: [state: Partial>]) => void; clear: (payload: [state: Partial>]) => void; update:modelValue: (payload: [value: AutoFormStateType | undefined]) => void; } ``` ### Expose You can access the typed component instance via [`useTemplateRef`](https://vuejs.org/api/composition-api-helpers.html#usetemplateref). | Name | Type | | --- | --- | | `reset()` | `void`
Restore the baseline and apply schema defaults | | `clear()` | `void`
Clear the form and keep schema defaults | | `formRef` | `Ref \| null>`
Template ref of the UForm component, provides access to all underlying form methods and properties | > [!TIP] > See: https://ui.nuxt.com/docs/components/form#expose > > Through > > formRef > > you can access all UForm underlying functionality, including > > submit() > > , > > validate() > > , > > clear() > > , > > getErrors() > > , > > setErrors() > > methods, and reactive properties such as > > errors > > , > > disabled > > , > > dirty > > , > > dirtyFields > > , > > touchedFields > > , > > blurredFields > > . See the Nuxt UI Form documentation for details. ## Theme ::component-theme{slug="AutoForm"} :: ## Changelog See commit history for [src/runtime/components/Quickstart.vue](https://github.com/mhaibaraai/movk-nuxt/commits/main/src/runtime/components/Quickstart.vue). # Recipes > Real-world AutoForm scenarios — login, grouped registration validation, multi-file upload and horizontal search form. ## Login Form Combine email, password and remember-me fields; `loadingAuto` manages the async submit state: ```vue [AutoFormRecipeLoginExample.vue] ``` ## Grouped Registration Validation Nest `object` fields to group them; `refine` validates that confirm password matches: ```vue [AutoFormRecipeRegisterExample.vue] ``` ## Multi-File Upload `afz.array(afz.file())` renders a multi-file field; after submission, summarize the attachment count: ```vue [AutoFormRecipeUploadExample.vue] ``` ## Horizontal Search Form `globalMeta` lays out filter items horizontally; the `footer` slot holds action buttons; `submit-button` disables the built-in button: ```vue [AutoFormRecipeSearchExample.vue] ``` # Field Types > Mapping of afz field types to controls and their configuration. ## String > [!NOTE] > See: https://zod.dev/api#strings > > Use > > afz.string() > > to create a string field: ### `Input` > [!NOTE] > See: https://ui.nuxt.com/docs/components/input > > Input component documentation Basic input field, configure icons, colors and other attributes via `controlProps`: ```vue [AutoFormFieldStringInputExample.vue] ``` ### `Textarea` > [!NOTE] > See: https://ui.nuxt.com/docs/components/textarea > > Textarea component documentation Multi-line text input, set `type: 'textarea'`, supports auto height adjustment: ```vue [AutoFormFieldStringTextareaExample.vue] ``` ### `PinInput` > [!NOTE] > See: https://ui.nuxt.com/docs/components/pin-input > > PinInput component documentation Verification code or PIN input, set `type: 'pinInput'`: ```vue [AutoFormFieldStringPinInputExample.vue] ``` ### `InputMenu` > [!NOTE] > See: https://ui.nuxt.com/docs/components/input-menu > > InputMenu component documentation Supports both typing and dropdown selection, set `type: 'inputMenu'`: ```vue [AutoFormFieldStringInputMenuExample.vue] ``` ### Dynamic Type Switch between input and textarea in an interactive example, and adjust size, color, rows and max length. ```vue [AutoFormFieldStringTypeExample.vue] ``` ## Number > [!NOTE] > See: https://zod.dev/api#numbers > > Use > > afz.number() > > to create a number field: ### `InputNumber` > [!NOTE] > See: https://ui.nuxt.com/docs/components/input-number > > InputNumber component documentation Basic number input, supports integer, decimal, range limits and other configurations: ```vue [AutoFormFieldNumberInputExample.vue] ``` ### `Slider` > [!NOTE] > See: https://ui.nuxt.com/docs/components/slider > > Slider component documentation Numeric slider, set `type: 'slider'`, suitable for selecting values within a defined range: ```vue [AutoFormFieldNumberSliderExample.vue] ``` ### `InputRating` > [!NOTE] > See: https://ui.nuxt.com/docs/components/input-rating > > InputRating component documentation Rating input, pass the `UInputRating` component instance directly via `component`, supports half-star granularity and customizable star count: ```vue [AutoFormFieldNumberInputRatingExample.vue] ``` ## Boolean > [!NOTE] > See: https://zod.dev/api#booleans > > Use > > afz.boolean() > > to create a boolean field: ### `Checkbox` > [!NOTE] > See: https://ui.nuxt.com/docs/components/checkbox > > Checkbox component documentation Default checkbox control, suitable for single option selection: ```vue [AutoFormFieldBooleanCheckboxExample.vue] ``` ### `Switch` > [!NOTE] > See: https://ui.nuxt.com/docs/components/switch > > Switch component documentation Toggle switch, set `type: 'switch'`, suitable for enabling/disabling features: ```vue [AutoFormFieldBooleanSwitchExample.vue] ``` ### `Toggle` Use `afz.boolean({ type: 'toggle' })` for a pressable button that represents a boolean, such as pinning a post. Set the button text with `controlProps.label`. ```vue [AutoFormFieldBooleanToggleExample.vue] ``` ## Date & Time > [!TIP] > See: /en/docs/components/date-picker#usedateformatter > > useDateFormatter documentation: a date formatting and handling utility based on @internationalized/date. Use `afz.calendarDate()` to create a date field, powered by [`@internationalized/date`](https://react-spectrum.adobe.com/internationalized/date/index.html) for robust date handling: ### Date Picker > [!NOTE] > See: https://ui.nuxt.com/docs/components/calendar > > Calendar component documentation Single date selection with date formatting and validation: ```vue [AutoFormFieldDatePickerExample.vue] ``` ### Date Range Date range selection, set `controlProps.range: true`: ```vue [AutoFormFieldDateRangeExample.vue] ``` ### Date Input > [!NOTE] > See: https://ui.nuxt.com/docs/components/input-date > > InputDate component documentation Use `afz.inputDate()` to create a date input field, based on the `UInputDate` component for a native date input experience. #### Single Date Input A clean date input field, suitable for form filling: ```vue [AutoFormFieldInputDateExample.vue] ``` #### Date Range Input A date input field with range selection support: ```vue [AutoFormFieldInputDateRangeExample.vue] ``` ### Time Input Use `afz.inputTime()` to create a time input field, returning the `Time` type (from `@internationalized/date`): > [!NOTE] > See: https://ui.nuxt.com/docs/components/input-time > > InputTime component documentation ```vue [AutoFormFieldInputTimeExample.vue] ``` ### ISO Format Strings For scenarios requiring ISO standard format strings, three factory methods are provided: - `afz.isoDate()` - validates `YYYY-MM-DD` format - `afz.isoTime()` - validates `HH:MM[:SS[.s+]]` format - `afz.isoDatetime()` - validates ISO 8601 full format ```vue [AutoFormFieldIsoExample.vue] ``` ## Enum > [!NOTE] > See: https://zod.dev/api#enums > > Use > > afz.enum() > > to create an enum field: > [!TIP] > > Used to override the default control and configure metadata, supporting three configuration approaches: > > Without specifying a control type, uses the default `select` control: > > ```ts > afz.enum(['a', 'b'], { > label: 'Select Option', > hint: 'Please choose one' > }) > ``` > > Override the default control via `type`, while keeping the output type unchanged: > > ```ts > afz.enum(['a', 'b', 'c'], { > type: 'radioGroup', // overrides the default select > controlProps: { > items: [ > { label: 'Option A', value: 'a' }, > { label: 'Option B', value: 'b' } > ] > } > }) > // Output type is still: 'a' | 'b' | 'c' > // but rendered using radioGroup > ``` > > Pass a custom component instance directly: > > ```ts > import MyEnumControl from './MyEnumControl.vue' > > afz.enum(['a', 'b'], { > component: MyEnumControl, > controlProps: { /* ... */ } > }) > ``` > [!TIP] > > Enum value configuration: `controlProps.items` takes the highest priority for rendered content, while the first argument of `enum()` determines the output type — both can be used together. > > - Method 1: Auto-extract enum values, the system automatically converts enum values to `items`:```ts > const Fruits = ['apple', 'banana', 'orange'] as const > > const schema = afz.object({ > fruit: afz.enum(Fruits, { > type: 'selectMenu', > controlProps: { > placeholder: 'Select a fruit' > // System auto-converts: items: ['apple', 'banana', 'orange'] > } > }) > }) > ``` > - Method 2: Provide items manually, use empty array `[]` as the first argument, fully controlled by `items` for type and rendering:```ts > const schema = afz.object({ > fruit: afz.enum([], { > type: 'selectMenu', > controlProps: { > valueKey: 'value', > items: [ > { label: 'Apple', value: 'apple' }, > { label: 'Banana', value: 'banana' } > ] > } > }) > }) > ``` > - Method 3: Type + custom display (recommended), use both the enum argument and `items` for type safety with custom display:```ts > const schema = afz.object({ > gender: afz.enum(['male', 'female', 'other'], { > type: 'radioGroup', > controlProps: { > items: [ > { label: 'Male', value: 'male' }, > { label: 'Female', value: 'female' }, > { label: 'Other', value: 'other' } > ] > } > }) > }) > // Output type: 'male' | 'female' | 'other' > // Display: Male / Female / Other > ``` ### `Select` > [!NOTE] > See: https://ui.nuxt.com/docs/components/select > > Select component documentation Native select box, suitable for simple enum values: ```vue [AutoFormFieldEnumSelectExample.vue] ``` ### `SelectMenu` > [!NOTE] > See: https://ui.nuxt.com/docs/components/select-menu > > SelectMenu component documentation Dropdown menu, set `type: 'selectMenu'`, supports search, icons, and grouping: ```vue [AutoFormFieldEnumSelectMenuExample.vue] ``` ### `RadioGroup` > [!NOTE] > See: https://ui.nuxt.com/docs/components/radio-group > > RadioGroup component documentation Radio button group, set `type: 'radioGroup'`, suitable for 2-4 options: ```vue [AutoFormFieldEnumRadioGroupExample.vue] ``` ### `ToggleGroup` Use `afz.enum(values, { type: 'toggleGroup' })` for a single-select button group. AutoForm creates items from the enum values. Pass `controlProps.items` to use custom labels. Pressing the selected option again clears it. Add `.optional()` to the schema if the field can be left empty. For multiple selection, use `afz.array()` with `type: 'toggleGroup'`, then pass `type: 'multiple'` and an array of item objects in `controlProps`. The field value is an array of the selected items' `value` properties. ```vue [AutoFormFieldToggleGroupExample.vue] ``` ## File > [!NOTE] > > Use > > afz.file() > > to create a file upload field: ### Single File Upload Basic single file upload: ```vue [AutoFormFieldFileSingleExample.vue] ``` ### Multiple File Upload Multiple file upload using `array` with `type: 'file'`: ```vue [AutoFormFieldFileMultipleExample.vue] ``` # Objects and Arrays > Rendering and editing nested object and dynamic array fields. ## Object > [!NOTE] > > Difference between two invocation styles > > ```ts > // Direct call > afz.object(shape, meta?) > > // Curried call (type parameter `` is for IDE hints only, does not affect runtime validation) > afz.object()(shape, meta?) > ``` > > ```ts > const schema = afz.object({ > name: afz.string(), > age: afz.number() > }) > ``` > > ```ts > interface UserInfo { > name: string > age: number > email: string > } > > const schema = afz.object()({ > name: afz.string(), // IDE will suggest name | age | email > email: afz.email() > }) > ``` ### Generic Object Generic object types are typically combined with `selectMenu` for selecting complex data structures: ```vue [AutoFormFieldObjectBasicExample.vue] ``` ### Nested Object Nested object structure with collapsible/expandable support: ```vue [AutoFormFieldObjectNestedExample.vue] ``` ### Typed Object > [!TIP] > > Use a TypeScript interface to constrain the object structure, getting IDE field name suggestions when defining the schema: ```vue [AutoFormFieldObjectTypedExample.vue] ``` > [!NOTE] > > Three object factories correspond to different extra key handling strategies: > > ```ts > const schema = afz.object({ name: afz.string() }) > > schema.parse({ name: 'John', extra: 'removed' }) > // Result: { name: 'John' } > ``` > > ```ts > const schema = afz.looseObject({ name: afz.string() }) > > schema.parse({ name: 'John', extra: 'kept' }) > // Result: { name: 'John', extra: 'kept' } > ``` > > ```ts > const schema = afz.strictObject({ name: afz.string() }) > > schema.parse({ name: 'John', extra: 'error' }) > // Error: Unrecognized key(s) in object: 'extra' > ``` ## Array > [!NOTE] > See: https://zod.dev/api#arrays > > Use > > afz.array() > > to create an array field: ### ElementSchema Defines the type of array elements, determining the output type as `T[]`: ```ts // String array const schema1 = afz.array(afz.string()) // Output type: string[] // Object array const schema2 = afz.array(afz.object({ name: afz.string(), age: afz.number() })) // Output type: { name: string, age: number }[] ``` ### Meta > [!NOTE] > > Used to > > override the default control of array elements > > and configure metadata, while keeping the output type unchanged: > [!TIP] > > For object arrays (e.g. `afz.array(afz.object({...}))`), the system automatically renders using collapsible panels — no need to manually specify a control type. > > Without specifying a control type, array elements use the default mapping: > > ```ts > afz.array(afz.string(), { > label: 'Tag List', > hint: 'Add multiple tags' > }) > // string[] - elements use the input control by default > ``` > > Override the **default control of array elements** via `type`, output type remains unchanged: > > ```ts > afz.array(afz.string(), { > type: 'checkboxGroup', // overrides the default input control for string > controlProps: { > items: ['reading', 'gaming', 'sports'] > } > }) > // Output type is still: string[] > // but rendered as checkboxGroup (multi-select) > ``` > > `afz.string()` would normally map to an `input` control. The `type: 'checkboxGroup'` in the second argument overrides this default mapping, changing it to a checkbox form. > > Pass a custom component instance directly: > > ```ts > import MyArrayControl from './MyArrayControl.vue' > > afz.array(afz.string(), { > component: MyArrayControl, > controlProps: { /* ... */ } > }) > ``` ### Async Options and Array Actions `asyncItems` reloads choices on `deps` changes. Pass the supplied `signal` to the request made by `load`. Set `sortable` and `duplicable` to move and duplicate entries. Schema `min`, `max` and `length` constrain additions and removals. ```vue [AutoFormAsyncItemsArrayExample.vue] ``` ### `InputTags` > [!NOTE] > See: https://ui.nuxt.com/docs/components/input-tags > > InputTags component documentation Tag input field, set `type: 'inputTags'`, suitable for free-text tags: ```vue [AutoFormFieldArrayInputTagsExample.vue] ``` ### `CheckboxGroup` > [!NOTE] > See: https://ui.nuxt.com/docs/components/checkbox-group > > CheckboxGroup component documentation Checkbox group, set `type: 'checkboxGroup'`, suitable for multi-selecting predefined options: ```vue [AutoFormFieldArrayCheckboxGroupExample.vue] ``` ### Object Array > [!NOTE] > See: https://ui.nuxt.com/docs/components/collapsible > > Collapsible component documentation Object arrays are automatically rendered using collapsible panels, supporting add and delete items: ```vue [AutoFormFieldArrayObjectExample.vue] ``` # Controls > Map schema fields to Nuxt UI controls via the type field, or register and inject custom Vue components to extend form fields. ## Overview AutoForm maps schema fields to specific rendering controls via the `type` field, and supports two ways to extend with custom controls: - **Register type**: Register a control type via `useAutoForm()`, then reference it in the schema via `type`, suitable for reusable controls - **Direct injection**: Pass a component instance directly via `component` in the schema, suitable for one-off usage ## Built-in Controls ### Default Mapping | afz Method | Default Control | Description | | --- | --- | --- | | `afz.string()` | `UInput` | Text input | | `afz.number()` | `UInputNumber` | Number input | | `afz.boolean()` | `UCheckbox` | Checkbox | | `afz.enum()` | `USelect` | Dropdown select | | `afz.file()` | `UFileUpload` | File upload | | `afz.calendarDate()` | `DatePicker` | Date picker | | `inputDate` | `UInputDate` | Date input | | `inputTime` | `UInputTime` | Time input | ### Available `type` Values Specify the following built-in controls in the schema via the `type` field: | type value | Control Component | Description | | --- | --- | --- | | `textarea` | `UTextarea` | Multi-line text input | | `switch` | `USwitch` | Toggle switch | | `toggle` | `UToggle` | Pressable button for a boolean value | | `slider` | `USlider` | Slider selector | | `pinInput` | `UPinInput` | PIN input | | `inputTags` | `UInputTags` | Tag input | | `selectMenu` | `USelectMenu` | Dropdown menu selector | | `inputMenu` | `UInputMenu` | Input menu | | `listbox` | `UListbox` | Listbox selector | | `checkboxGroup` | `UCheckboxGroup` | Checkbox group | | `radioGroup` | `URadioGroup` | Radio button group | | `toggleGroup` | `UToggleGroup` | Button group for single or multiple selection | | `inputDate` | `UInputDate` | Date input | | `inputTime` | `UInputTime` | Time input | > [!NOTE] > See: /en/docs/getting-started/migration > > v2 removed control types such as > > withClear > > , > > withPasswordToggle > > , > > colorChooser > > and > > pillGroup > > . See the migration guide for replacements. ### Controls Overview Reference built-in controls in the schema via `type`, demonstrating all built-in controls grouped by text, number, boolean, selection and date: ```vue [AutoFormControlsExample.vue] ``` ## Custom Controls When built-in controls cannot meet your needs, you can integrate custom Vue components through registration or direct injection. ### Register a Control Register a control via `useAutoForm()`, then reference it in the schema via the `type` field: ```ts import { TagSelector } from '#components' const { afz, controls } = useAutoForm({ tagSelector: defineControl({ component: TagSelector, controlProps: { class: 'w-full' } // global controlProps (can be overridden at field level) }) }) ``` > [!TIP] > > It is recommended to use > > defineControl > > to register custom controls for more stable > > controlProps > > / > > controlSlots > > type hints. > [!NOTE] > > The plain object syntax ( > > tagSelector: { component: TagSelector } > > ) is still supported and also benefits from type inference. Use the registered control type in the schema: ```ts const schema = afz.object({ skills: afz .array(afz.string(), { type: 'tagSelector', // specify control type controlProps: { options: ['Vue.js', 'Nuxt', 'TypeScript'], max: 5 } }) .meta({ label: 'Skill Tags' }) }) ``` Pass `controls` to `MAutoForm`: ```vue ``` ### Inject Component Directly Pass a component instance directly in the schema metadata, for example `UInputRating`. ```ts import { UInputRating } from '#components' const schema = afz.object({ rating: afz.number({ component: UInputRating, controlProps: { length: 10 } }).meta({ label: 'Rating' }) }) ``` > [!NOTE] > > When injecting a component directly, > > type > > and > > component > > are mutually exclusive; if both are present, > > component > > takes precedence. ### Component Specification Custom control components must meet the following requirements. #### Support v-model ```vue ``` #### Accept controlProps Fields in `controlProps` are passed through as props to the control component. The component should declare the corresponding props: ```vue ``` ## Example Register `TagSelector` as the `tagSelector` control type via `defineControl`, reference it with `type: 'tagSelector'` in the schema, and pass candidate tags and maximum selection count via `controlProps`: ```vue [AutoFormCustomControlExample.vue] ``` ```vue [app/components/TagSelector.vue] ``` # Metadata and Layout > Configure field properties through meta and arrange them with afz.layout. ## Metadata ### `meta` Field Metadata > [!NOTE] > See: https://ui.nuxt.com/docs/components/form-field#props > > View all available metadata attributes, types and configuration priority. ```vue [AutoFormMetadataExample.vue] ``` ### `globalMeta` Global Metadata ```vue [AutoFormAdvancedGlobalMetaExample.vue] ``` ## Layout ### Examples #### Simple Container Layout Use `afz.layout` to create a basic container layout, controlling styles via the `class` attribute: ```vue [AutoFormLayoutSimpleExample.vue] ``` > [!NOTE] > > It is conventional for layout field keys (e.g. > > $layout > > ) to start with > > $ > > , but it is not required. You can use any field name as long as its value is > > afz.layout() > > . #### Grid Layout Use CSS Grid to create multi-column layouts, controlling column spans via field-level `class`: ```vue [AutoFormLayoutGridExample.vue] ``` #### Responsive Multi-Column Layout Use Tailwind's responsive prefixes to create layouts that adapt to different screen sizes: ```vue [AutoFormLayoutResponsiveExample.vue] ``` > [!TIP] > > Use Tailwind's responsive prefixes ( > > md: > > , > > lg: > > ) to easily achieve cross-device adaptive layouts. Fields can span the full row with > > col-span-full > > . #### Nested Layout Layout fields can be nested infinitely to build complex hierarchical structures: ```vue [AutoFormLayoutNestedExample.vue] ``` > [!WARNING] > > There is no limit to nested layout depth, but deep nesting can hurt readability. Keeping it to 2-3 levels is recommended. #### Accordion Layout Use Nuxt UI's `UAccordion` component to organize fields in collapsible panels: ```vue [AutoFormLayoutAccordionExample.vue] ``` > [!TIP] > > fieldSlots > > is used to assign different fields to different slots of the layout component. Slot names must match the > > slot > > defined in > > items > > . #### Tabs Layout Use the `UTabs` component to create a tabbed form with dynamic responsive configuration: ```vue [AutoFormLayoutTabsExample.vue] ``` > [!TIP] > > The tabs layout demonstrates how to dynamically adjust the layout structure based on form state. When switching user types, tab titles and field distribution update automatically. > [!WARNING] > > When using conditional rendering ( > > if > > ), it is recommended to mark fields as > > .optional() > > to avoid validation errors. ### API #### `AutoFormLayoutConfig` `afz.layout` accepts a configuration object with the following attributes: | Attribute | Type | Description | | --- | --- | --- | | `component` | `Component \| string` | Layout container component (default: `'div'`) | | `class` | `string \| (context) => string` | CSS class name, supports reactive function | | `props` | `object \| (context) => object` | Component attributes, supports reactive function | | `slots` | `Record VNode> \| (context) => ...` | Component slot content | | `fields` | `Record` | Contained field definitions | | `fieldSlot` | `string \| (context) => string` | Render **all** fields into the specified slot | | `fieldSlots` | `Record \| (context) => ...` | Assign **different** fields to different slots | #### `AutoFormNestedCollapsible` The `collapsible` attribute accepts a configuration object with the following options: | Attribute | Type | Default | Description | | --- | --- | --- | --- | | `enabled` | `boolean` | `true` | Whether to enable collapsible functionality | | `defaultOpen` | `boolean` | | Whether to be open by default | | `open` | `boolean` | | Control expand/collapse state (controlled mode) | | `disabled` | `boolean` | | Disable collapsible (always expanded) | | `unmountOnHide` | `boolean` | `true` | Unmount content when hidden | | `as` | `string` | `'div'` | Rendered element type | | `class` | `ClassNameValue` | | CSS class name | | `ui` | `{ root?: ClassNameValue; content?: ClassNameValue; }` | | UI style configuration | # Slots > Customize AutoForm's header/footer, field controls, before/after field and layout content via named slots. ## Overview The `AutoForm` slot system is organized into three levels: - **Form slots** - Customize the overall form structure (`header`, `footer`, `submit`) - **Field slots** - Fine-tune individual parts of each field (`field-label`, `field-hint`, `field-error`, etc.) - **Content slots** - Take over the rendering of object and array fields, or insert content before/after fields (`field-content`, `field-before`, `field-after`) > [!TIP] > > Field slots support both the > > generic pattern > > field-{type} > > and the > > named pattern > > field-{type}:{path} > > , allowing you to unify styles while precisely controlling specific fields. Named patterns take priority over generic patterns. ## Examples ### Form Level `header`, `footer`, and `submit` take over the form's head, footer and submit area — all can read `loading`, `errors`, `state` to customize the outer layer. > [!WARNING] > > When using the > > submit > > slot, set > > :submit="false" > > to disable the default submit button, otherwise it will be rendered twice. ```vue [AutoFormSlotsFormExample.vue] ``` ### Generic Field `field-label`, `field-description`, `field-hint`, `field-error` uniformly override the label, description, hint and error areas of all fields. ```vue [AutoFormSlotsGenericExample.vue] ``` ### Named Field `field-{type}:{path}` replaces only the specified area of a given field; unmatched fields keep their default rendering. `field-default:{path}` completely replaces the control for that field. > [!NOTE] > > Named slot priority is higher than generic slots: when both > > field-label > > and > > field-label:username > > exist, the > > username > > field uses the latter. ```vue [AutoFormSlotsKeyedExample.vue] ``` ### Before / After Field `field-before:{path}` and `field-after:{path}` append content before and after the default field content without taking over child field rendering and interaction. ```vue [AutoFormSlotsBeforeAfterExample.vue] ``` ### Object Content `field-content:{path}` completely replaces the rendering of an object field; use `setValue('key', value)` with a relative key to update child fields. ```vue [AutoFormSlotsObjectContentExample.vue] ``` ### Array Content `field-content:{path}` replaces the rendering of an array field; `setValue` can write the entire list or update a single item using an `[index].key` path. ```vue [AutoFormSlotsArrayContentExample.vue] ``` ## API ### Form-Level Slots | Name | Description | | --- | --- | | `header` | Above the fields area, suitable for titles, descriptions or status hints | | `footer` | Below the fields area, above the submit button | | `submit` | Takes over the submit area, use with `:submit="false"` | ### Field Slots | Slot | Parameter | Type | Description | | --- | --- | --- | --- | | `field-label` | `label` | `string` | Label text | | `field-hint` | `hint` | `string` | Hint text | | `field-description` | `description` | `string` | Description text | | `field-help` | `help` | `string` | Help text | | `field-error` | `error` | `string \| boolean` | Error message | | `field-default` | `error` | `string \| boolean` | Takes over control rendering for primitive type fields (with field context) | > [!TIP] > > field-default > > is only for customizing the control of primitive type fields (string, number, boolean, etc.). For object and array fields, use > > field-content > > . ### Content Slots > [!WARNING] > > Content slots only apply to > > object fields and array fields > > and have no effect on primitive type fields. | Name | Description | | --- | --- | | `field-content:{path}` | Completely takes over the rendering of an object/array field | | `field-before:{path}` | Inserts before the default content without taking over child fields | | `field-after:{path}` | Inserts after the default content without taking over child fields | ### `setValue` Signature `setValue` supports the following overload forms: | Signature | Return | Description | | --- | --- | --- | | `setValue(value)` | `void` | Set the entire field value | | `setValue(relativePath, value)` | `void` | Update a child field by relative path: use key for objects (auto-inferred), `[index].key` for arrays | > [!NOTE] > > ```vue > // Set the current field value directly > setValue(newValue) > ``` > > ```vue > > ``` > > ```vue > > ``` ### `AutoFormFieldContext` Field context type, available in slots and reactive functions: ```ts export interface AutoFormFieldContext { /** Form data */ readonly state: S /** Field path */ readonly path: P /** Field value (may be undefined) */ readonly value: FieldValueType /** * Callback function to set the field value * @description Supports multiple invocation styles: * 1. setValue(value) - set the entire value of the current field * 2. setValue(key, value) - set a child field value (object) or element property (array) * 3. setValue(path, value) - set a value at an arbitrary path (string fallback) * @example * // Object field profile: { name, email, bio } * setValue({ name: 'John', email: 'test@example.com' }) // set the entire object * setValue('name', 'John') // key auto-inferred as 'name' | 'email' | 'bio' * * // Array field tasks: [{ title, priority, completed }] * setValue([...tasks, newTask]) // set the entire array * setValue('[0].title', 'New Title') // use index path string * * // Or use property name directly when iterating (recommended) * v-for="(task, index) in tasks" * setValue(`[${index}].title`, value) // dynamic index */ setValue: { (value: FieldValueType): void >>( relativePath: K extends never ? string : K, value: any ): void (relativePath: string, value: any): void } /** Field error list */ readonly errors: unknown[] /** Form submit loading state */ readonly loading: boolean /** Field collapsed state */ readonly open?: boolean /** Array element index */ readonly count?: number } ``` # Reactivity and Submit > Reactive linkage between fields and form submission handling. ## Reactive & Conditional ### Overview All meta fields in AutoForm can accept **reactive functions** `(ctx) => value`, where `ctx` is the [`AutoFormFieldContext`](https://nuxt.mhaibaraai.me/en/docs/auto-form/slots#autoformfieldcontext) (containing `state`, `path`, `value`). The function re-evaluates automatically as the form state changes, enabling conditional rendering and field dependencies. > [!NOTE] > > There are two ways to conditionally render, with different behaviors: > > - **`if`** - Display condition; when `false` the field is **not created** (not mounted, not included in validation). > - **`hidden`** - Whether to hide; when `true` the field **remains in the DOM and form data**, only visually hidden. ### Examples #### Conditional Rendering `if` and `hidden` accept functions returning a boolean: when switching account type, business fields (`if`) are mounted/unmounted on demand; after checking the terms, the subscription field (`hidden`) switches from hidden to visible. > [!TIP] > > Use > > if > > when you want to completely exclude a field (no validation, not submitted); use > > hidden > > when you want to temporarily hide it but retain its value. ```vue [AutoFormReactiveConditionalExample.vue] ``` #### Dependent Fields When control props depend on reactive state in the component, omit the callback parameter. Literal values are inferred from the control props, as in `afz.string({ controlProps: () => ({ size: compact.value ? 'sm' : 'lg' }) })`. Functional `controlProps` re-evaluates as other fields change. In the example below, city options depend on the country field, and a `watch` clears the stale value when the country changes. > [!NOTE] > > Field dependencies only re-evaluate control attributes and will not automatically clear old values. Use > > watch > > to manually reset stale options when needed. ```vue [AutoFormReactiveDependentExample.vue] ``` > [!NOTE] > > When `items` comes from **async or external reactive data** (e.g. a `computed` / `ref` based on `useApiFetch` or `useAsyncData`), always use **functional** `controlProps: () => ({ items: source.value })`, or pass the reactive source directly as `items: source` — never write `items: source.value`. > > The schema is only constructed once during `setup`, so `source.value` is a one-time snapshot at that moment. This may appear to work during SSR hydration when data is ready, but will freeze to an empty array when the component re-mounts during client-side navigation before async data arrives, and subsequent option updates will no longer take effect. Functional `controlProps` evaluates at render time and avoids this problem. ### API #### `meta` | Name | Type | Description | | --- | --- | --- | | `if` | `ReactiveValue` | Display condition; field is not created when `false` | | `hidden` | `ReactiveValue` | Whether to hide; retains DOM but visually hidden when `true` | > [!TIP] > > In addition to the above fields, > > label > > , > > hint > > , > > description > > , > > controlProps > > , > > class > > and other meta fields also support the > > (ctx) => value > > function form, dynamically evaluated based on form state. ## Submit ### `loadingAuto` When `@submit` returns a Promise, the submit button loading state is managed automatically by AutoForm (`loadingAuto` is enabled by default): ```vue [AutoFormSubmitAutoExample.vue] ``` ### Manual Loading Control Disable `loading-auto` and let `submit-button-props.loading` take over the button state: ```vue [AutoFormSubmitManualExample.vue] ``` ### Async Errors and Validation Events Handle async errors in `@submit`; `@error` receives field validation failures: ```vue [AutoFormSubmitErrorExample.vue] ``` ### Programmatic Submit Get the form instance via `useTemplateRef`, then trigger `formRef.submit()`, `reset()`, `clear()` externally (use `:submit="false"` to hide the built-in button): ```vue [AutoFormSubmitRefExample.vue] ``` # SearchForm > A schema-driven, collapsible search form component. ## Introduction `MSearchForm` is a schema-driven search form component with built-in grid layout, search/reset buttons, and collapse behavior. When there are many search fields, items exceeding the visible row count are automatically collapsed. Users can expand or collapse them using the toggle button. > [!NOTE] > See: /en/docs/auto-form/quickstart > > Reuses the AutoForm infrastructure (schema introspection, control mapping, field renderers) and defines search fields via Zod schema. ## Usage Renders fields from an AutoForm schema. `cols` controls the grid. Built-in search and reset buttons — clicking "Search" triggers validation and emits `@submit`: ```vue [ComponentsSearchFormBasicExample.vue] ``` ### `v-model` Binding `v-model` binds form data bidirectionally. The initial value passed in is recorded as the reset baseline — clicking "Reset" restores to that initial value rather than clearing the form. ```vue [ComponentsSearchFormModelExample.vue] ``` ### `cols` Grid Columns `cols` controls the number of grid columns: pass a number for a fixed count, or a breakpoint object to switch columns across `sm`, `md`, `lg`, `xl` breakpoints. ```vue [ComponentsSearchFormColsExample.vue] ``` ```vue [ComponentsSearchFormResponsiveExample.vue] ``` ### `visibleRows` Collapse Behavior `visibleRows` controls the number of visible rows. Fields exceeding this count collapse into the expanded area. Drag `cols` and `visibleRows` below to change the collapse threshold in real time. ```vue [ComponentsSearchFormExpandExample.vue] ``` ### `v-model:expanded` Controlled Expand `v-model:expanded` takes over the expanded state, taking priority over `defaultExpanded`. It can be driven by external buttons or logic. ```vue [ComponentsSearchFormExpandedControlledExample.vue] ``` ### `expandText` / `collapseText` / `icon` Toggle Button `expandText` and `collapseText` customize the expand/collapse label text. `icon` switches the button icon. `collapseButtonProps` passes through button attributes. ```vue [ComponentsSearchFormToggleButtonExample.vue] ``` ### `actions` Action Buttons The `actions` array extends or trims buttons: - Built-in `key: search` automatically binds to submit; `key: reset` automatically binds to reset - Custom `key` requires an `onClick(ctx)` handler where `ctx` contains `state`, `errors`, `search`, `reset`, `clear`, `toggle`, `loading`, and `expanded` - Pass `actions: []` to disable all built-in buttons and fully customize via the `actions` slot ```vue [ComponentsSearchFormHideButtonsExample.vue] ``` ```vue [ComponentsSearchFormCustomExample.vue] ``` ## Examples ### Taking Over the Actions Area The `#actions` slot exposes `search`, `clear`, and `loading`, allowing custom buttons to replace the default actions area: ```vue [ComponentsSearchFormActionsSlotExample.vue] ``` ### Extending Layout Areas `header`, `footer`, and `extraActions` insert supplementary content. Slot props update with expand state and form values: ```vue [ComponentsSearchFormLayoutSlotsExample.vue] ``` ### Async Submit and Validation `loading` controls the button loading state. `@error` returns the list of Zod validation failures: ```vue [ComponentsSearchFormAsyncExample.vue] ``` ### URL Search History `syncQuery` restores top-level schema fields from the URL in Nuxt and Vue Router. Use `replace: false` to add a history entry on submit, reset or clear. Listen to `query-restore` to refresh results from the restored fields. Inertia and no-router mode support the standard form. ```vue [AutoFormSearchFormQueryExample.vue] ``` ## API ### Props ```ts /** * Props for the MSearchForm component */ interface MSearchFormProps { /** * Zod 对象 schema,定义表单字段 */ schema: S; /** * Nuxt 或 Vue Router 下同步 schema 顶层字段:挂载和路由变化时读取,提交、重置、清空时写入 * @default false */ syncQuery?: boolean | SearchFormQuerySync | undefined; /** * 提交前清洗载荷:`true` 时去除字符串首尾空白并剔除空值,传函数可自定义;`false` 时原样提交 * @default true */ transformPayload?: boolean | ((data: Partial>) => Partial>) | undefined; /** * 网格列数 * @default 3 */ cols?: number | { sm?: number | undefined; md?: number | undefined; lg?: number | undefined; xl?: number | undefined; } | undefined; /** * 可见行数(折叠时显示的行数) * @default 1 */ visibleRows?: number | undefined; /** * 动作按钮配置;不传时使用默认 [search, reset];传 [] 则关闭所有内置按钮 * @default [{ key: 'search', ... }, { key: 'reset', ... }] */ actions?: SearchFormAction[] | undefined; /** * 外部 loading 状态,与提交中状态合并,作用于 type==='submit' 或 key==='search' 的按钮 */ loading?: boolean | undefined; /** * 收起按钮属性 */ collapseButtonProps?: ButtonProps | undefined; /** * 展开/收起按钮图标 * @default 'i-lucide-chevron-down' */ icon?: any; /** * 展开按钮文本,缺省时取 locale 的 `searchForm.expand` */ expandText?: string | undefined; /** * 收起按钮文本,缺省时取 locale 的 `searchForm.collapse` */ collapseText?: string | undefined; /** * 默认展开状态 * @default false */ defaultExpanded?: boolean | undefined; /** * 自定义控件映射 */ controls?: AutoFormControls | undefined; /** * 全局字段元数据配置 */ globalMeta?: ZodAutoFormFieldMeta | undefined; /** * 是否启用自动 loading 功能。 * @default true */ loadingAuto?: boolean | undefined; /** * 表单验证时机,详见 UForm 的 validateOn 属性 * @default [] */ validateOn?: FormInputEvents[] | undefined; /** * 字段被 `meta.if` 隐藏时如何处理其值:`keep` 保留,`clear` 置为 `undefined`;字段 meta 的 `hiddenValue` 优先。 * 无论哪种策略,隐藏字段都不参与校验,也不出现在提交数据中 * @default 'keep' */ hiddenValue?: "clear" | "keep" | undefined; /** * 提交回调;返回 Promise 时配合 `loadingAuto` 显示加载状态 */ onSubmit?: (): void | (event: FormSubmitEvent>): void | undefined; ui?: Record & { root?: SlotClass; form?: SlotClass; visible?: SlotClass; grid?: SlotClass; header?: SlotClass; footer?: SlotClass; actions?: SlotClass; toggleWrapper?: SlotClass; toggle?: SlotClass; toggleIcon?: SlotClass; collapsed?: SlotClass; } | undefined; id?: string | number | undefined; /** * Custom validation function to validate the form state. */ validate?: (state: Partial>): FormError[] | Promise[]> | undefined; /** * Disable all inputs inside the form. */ disabled?: boolean | undefined; /** * The `name` attribute of the form element. * For nested forms (`nested` is true), this is also used as the path of the form's state within its parent form. */ name?: string | undefined; /** * Delay in milliseconds before validating the form on input events. * @default `300` */ validateOnInputDelay?: number | undefined; /** * If true, applies schema transformations on submit. * @default `true` */ transform?: true | undefined; /** * If true, this form will attach to its parent Form and validate at the same time. * @default `false` */ nested?: false | undefined; acceptcharset?: string | undefined; action?: string | undefined; autocomplete?: string | undefined; enctype?: string | undefined; method?: string | undefined; novalidate?: false | true | "true" | "false" | undefined; target?: string | undefined; /** * @default {} */ modelValue?: Partial> | undefined; expanded?: boolean | undefined; } ``` ### Emits ```ts /** * Emitted events for the MSearchForm component */ interface MSearchFormEmits { reset: (payload: [state: Partial>]) => void; clear: (payload: [state: Partial>]) => void; expand: (payload: [expanded: boolean]) => void; query-restore: (payload: [state: Partial>]) => void; error: (payload: [event: FormErrorEvent]) => void; update:modelValue: (payload: [value: Partial>]) => void; update:expanded: (payload: [value: boolean | undefined]) => void; } ``` > [!NOTE] > > @submit > > is forwarded from the underlying > > UForm > > and is not listed in the table above. It fires after successful validation and returns a > > FormSubmitEvent > > where search conditions are in > > event.data > > — the primary outlet for receiving query parameters. ### Slots ```ts /** * Slots for the MSearchForm component */ interface MSearchFormSlots { header(): any; footer(): any; actions(): any; extraActions(): any; field-label(): any; field-hint(): any; field-description(): any; field-help(): any; field-error(): any; field-default(): any; } ``` ### Expose You can access the typed component instance via [`useTemplateRef`](https://vuejs.org/api/composition-api-helpers.html#usetemplateref). | Name | Type | | --- | --- | | `formRef` | `Ref>`
Reference to the UForm component | | `submit()` | `void`
Programmatically trigger form submission (equivalent to clicking the search button) | | `reset()` | `void`
Restore to baseline (the v-model snapshot from initial mount) and fire the `reset` event | | `clear()` | `void`
Clear all form fields to empty values and fire the `clear` event | | `setBaseline(value?)` | `void`
Set the restore baseline for `reset()`; uses the current v-model value if no argument is passed | | `expanded` | `ComputedRef`
Current expanded/collapsed state | | `toggle()` | `void`
Toggle expand/collapse and emit `expand` and `update:expanded` | ## Theme ::component-theme :: ## Changelog See commit history for [src/runtime/components/SearchForm.vue](https://github.com/mhaibaraai/movk-nuxt/commits/main/src/runtime/components/SearchForm.vue). # useAutoForm > A composable for creating typed Zod schemas and managing AutoForm controls. ## Usage Use the auto-imported `useAutoForm` composable to create typed Zod schemas and provide validation rules and control configuration for the [`AutoForm`](https://nuxt.mhaibaraai.me/en/docs/auto-form/quickstart) component. ```vue ``` - `useAutoForm` returns the enhanced Zod factory object `afz`, which supports attaching AutoForm metadata to schemas. - Metadata is automatically persisted through Zod's chained calls (e.g. `.optional()`, `.nullable()`, `.default()`, etc.). > [!NOTE] > > Schemas created with the > > afz > > factory intercept Zod's clone methods to ensure metadata is not lost during chained calls. ## Custom Control Registration When using custom controls, define them with the `defineControl` helper: ```ts const { afz, defineControl } = useAutoForm({ myInput: defineControl({ component: MyCustomInput, controlProps: { class: 'w-full' } }) }) // Now usable in a schema const schema = afz.string({ type: 'myInput', controlProps: { variant: 'outline' } }) ``` ## API ### useAutoForm() `useAutoForm(controls?: AutoFormControls): UseAutoFormReturn`{lang="ts-type"} Creates an AutoForm factory and control manager. #### Parameters **controls** (`AutoFormControls`): Custom control mapping object used to extend or override default controls, defined with defineControl (see "Custom Control Registration" above). #### Returns **afz** (`TypedZodFactory`): Typed Zod factory object for creating schemas with metadata. **defineControl** (`Function`): Helper function for defining controls. **DEFAULT_CONTROLS** (`Object`): Default control mapping object. **controls** (`Object`): The custom control mapping passed in. **getAutoFormMetadata** (`Function`): Utility function to extract custom metadata from a schema. ## Changelog See commit history for [src/runtime/composables/useAutoForm.ts](https://github.com/mhaibaraai/movk-nuxt/commits/main/src/runtime/composables/useAutoForm.ts). # Introduction > A declarative data table based on TanStack Table, with column configuration, selection, expansion, tree data, pagination, load more and complete API reference. ## Overview `MDataTable` is a declarative data table built on [`@tanstack/vue-table`](https://tanstack.com/table) and Nuxt UI `UTable`. It consolidates column definitions, sorting, column pinning, column resize, selection, expansion, tree data, pagination and load more into a single `columns` array and a handful of props, while providing complete TypeScript type inference. > [!NOTE] > > Core philosophy: > > - **Declarative columns** — Describe columns with an array of objects; data columns, selection columns, index columns, expand columns, actions columns and group columns are distinguished by `accessorKey` or `type`. > - **Global + per-column toggles** — `sortable`, `pinable`, `resizable`, `truncate`, `tooltip` and others can be enabled globally and overridden per column, or driven by a function for dynamic behavior. > - **Type-safe** — Columns, cell callbacks and event handlers are all driven by types such as `DataTableColumn` and `DataTableProps`. ## Usage A single `columns` array is enough to declare selection columns, index columns, fixed columns, cell rendering and actions columns. Combine with `row-key` for row identification, `sortable`/`pinable`/`resizable` for sorting, column pinning and column resize, and `v-model:pagination` for pagination — no manual assembly required: ```vue [DataTableBasicExample.vue] ``` ## Sample Data All examples in this chapter derive their `data` from the following utility function. You can copy it directly into your project: ```ts [app/composables/useTableMock.ts] export interface Person { id: string name: string email: string department: 'R&D' | 'Design' | 'Product' | 'Operations' | 'Marketing' role: string level?: 'P5' | 'P6' | 'P7' | 'P8' status: 'active' | 'leave' | 'offboarded' salary: number joinedAt: string address: string bio: string children?: Person[] } const FIRST = ['Zhang', 'Li', 'Wang', 'Chen', 'Liu', 'Yang', 'Huang', 'Zhao', 'Wu', 'Zhou', 'Xu', 'Sun'] const LAST = ['Wei', 'Fang', 'Na', 'Min', 'Jing', 'Li', 'Qiang', 'Lei', 'Jun', 'Yang', 'Yong', 'Tao', 'Ming', 'Chao'] const DEPARTMENTS: Person['department'][] = ['R&D', 'Design', 'Product', 'Operations', 'Marketing'] const ROLES = ['Frontend Engineer', 'Backend Engineer', 'Full Stack Engineer', 'UI Designer', 'Product Manager', 'Data Analyst', 'Operations Specialist'] const LEVELS: Person['level'][] = ['P5', 'P6', 'P7', 'P8'] const STATUS: Person['status'][] = ['active', 'leave', 'offboarded'] const ADDRESSES = [ '708, IBM Tower, 2 Boyun Rd, Zhangjiang Hi-Tech Park, Pudong, Shanghai', '1502, Zhongguancun Tower A, 27 Zhongguancun St, Haidian, Beijing', '2301, Block B, Bay Technology Ecology Park, 9 Gaoxin Nan 9th Rd, Nanshan, Shenzhen', '38F, R&F Yingkai Plaza, 16 Huaxia Rd, Pearl River New Town, Tianhe, Guangzhou', '318, Building 6, Alibaba Xixi Campus, 969 Wenyi W Rd, Yuhang, Hangzhou', '1207, Building 5, Block D, Tianfu Software Park, 1199 Tianfu Ave, Hi-Tech Zone, Chengdu', '19F, Gaoke Rongyu Tower, 222 Jiangdong Zhong Rd, Jianye, Nanjing', '1808, Block B, Phase 3, Optics Valley International Enterprise Center, 70 Optics Valley Ave, Hongshan, Wuhan' ] const BIO_TEMPLATES = [ 'Led supply chain and fulfillment infrastructure for a cross-border e-commerce team; spearheaded a real-time scheduling system overhaul handling millions of daily orders, with a focus on stability and cost efficiency.', 'Long-term investment in big data platforms and offline computation scheduling; built a PB-scale data warehouse and governance framework with strong experience in data quality and access control.', 'Focused on design systems and component libraries, driving visual consistency across products and leading multiple Design Token and dark-mode rollouts.', 'Responsible for an in-house low-code platform and BFF middleware layer; delivered internal scaffolding and CLI tooling with an emphasis on developer productivity and maintainability.', 'Deep expertise in real-time audio/video and WebRTC interactive scenarios; led latency optimization and weak-network degradation strategies for live rooms with tens of millions of concurrent users.', 'Owned permissions, billing and multi-tenancy for a B2B SaaS product with full end-to-end experience in RBAC, ABAC and compliance auditing.', 'Engineered risk control and anti-abuse algorithms; built real-time feature platforms and rules engines covering payment, marketing and social scenarios.', 'Focused on mobile performance optimization and cross-platform rendering frameworks; led end-to-end governance of startup time, memory usage and bundle size.' ] function pick(list: readonly T[], seed: number): T { return list[seed % list.length] as T } export function makePerson(seed: number): Person { const first = pick(FIRST, seed) const last = pick(LAST, seed * 31 + 7) const dept = pick(DEPARTMENTS, seed * 7) return { id: `P${String(seed).padStart(4, '0')}`, name: `${first} ${last}`, email: `user${seed}@movk.dev`, department: dept, role: pick(ROLES, seed * 3), level: pick(LEVELS, seed * 11), status: pick(STATUS, seed * 13), salary: 8000 + (seed * 257) % 50000, joinedAt: new Date(2018 + (seed % 7), seed % 12, 1 + (seed % 27)).toISOString().slice(0, 10), address: pick(ADDRESSES, seed * 17), bio: pick(BIO_TEMPLATES, seed * 19) } } export function makePeople(count: number, offset = 0): Person[] { return Array.from({ length: count }, (_, i) => makePerson(offset + i + 1)) } export function makePeopleTree(rootCount = 5, childPerRoot = 3, depth = 1): Person[] { const build = (seed: number, level: number): Person => { const person = makePerson(seed) if (level >= depth) return person return { ...person, role: 'Team Lead', level: undefined, children: Array.from({ length: childPerRoot }, (_, j) => build(seed * 100 + j + 1, level + 1)) } } return Array.from({ length: rootCount }, (_, i) => build(i + 1, 0)) } ``` ## API ### Props ```ts /** * Props for the MDataTable component */ interface MDataTableProps { /** * 行唯一标识字段,自动派生 getRowId;与 getRowId 同传时后者优先 */ rowKey?: string & {} | keyof T & string | undefined; columns?: DataTableColumn[] | undefined; loading?: boolean | undefined; /** * 加载中且无数据时显示的骨架行数,`0` 时沿用 UTable 默认的加载样式;`loading` 插槽优先 * @default 5 */ skeletonRows?: number | undefined; /** * 在表格上方的工具栏显示列设置面板(显隐与拖拽排序) * @default false */ columnSettings?: boolean | undefined; /** * 设置后将列可见性、顺序、宽度、固定与每页条数持久化到 localStorage,值作为存储 key */ persistKey?: string | undefined; /** * 服务端全量 CSV 下载回调,应使用应用当前的外部筛选条件及表格传入的查询条件 */ serverCsvExport?: (context: DataTableServerCsvContext): void | Promise | undefined; /** * 斑马纹 * @default false */ stripe?: boolean | undefined; /** * 纵向边框,传对象可定制 color/width/style * @default false */ bordered?: boolean | { color?: string | undefined; width?: string | undefined; style?: "solid" | "dashed" | "dotted" | "double" | undefined; } | undefined; /** * 表格宽度由列宽内容决定(w-fit) * @default false */ fitContent?: boolean | undefined; /** * 空值占位符 * @default '-' */ emptyCell?: string | false | (props: CellContext): any | undefined; /** * 启用列固定按钮,传函数可按列动态决定 * @default false */ pinable?: boolean | ((col: DataTableDataColumn) => boolean) | undefined; pinButtonProps?: ButtonProps | (ctx: DataTablePinButtonContext): ButtonProps | undefined; /** * 启用列排序,传函数可按列动态决定 * @default false */ sortable?: boolean | ((col: DataTableDataColumn) => boolean) | undefined; sortButtonProps?: ButtonProps | (ctx: DataTableSortButtonContext): ButtonProps | undefined; /** * 全局 action 按钮 props,与列级 action.buttonProps 深度合并,列级优先 */ actionButtonProps?: ButtonProps | (ctx: DataTableActionButtonContext): ButtonProps | undefined; /** * 行内最多展示多少 action 按钮,超出折叠到 overflow * @default 3 */ actionsMaxInline?: number | undefined; actionsOverflowTrigger?: ButtonProps | (ctx: CellContext): ButtonProps | undefined; /** * 启用列宽拖拽,传函数可按列动态决定 * @default false */ resizable?: boolean | ((col: DataTableDataColumn) => boolean) | undefined; /** * - 'onChange' 拖动中实时重排 * - 'onEnd' 释放后才更新 * @default 'onChange' */ columnResizeMode?: "onChange" | "onEnd" | undefined; /** * 单元格内边距密度 */ density?: "compact" | "normal" | "comfortable" | { th?: string | ((cell: Header) => string) | undefined; td?: string | ((cell: Cell) => string) | undefined; } | undefined; meta?: TableMeta | undefined; rowClass?: string | (row: T): string | undefined; rowStyle?: string | Record | (row: T): string | Record | undefined; /** * 单元格溢出 Tooltip:true 单行 / number 多行 / false 禁用 / 函数 动态 * @default false */ tooltip?: number | false | true | (ctx: CellContext): number | boolean | undefined; tooltipProps?: OmitByKey | undefined; /** * 单元格文本截断:true 单行 / number 多行 / false 禁用 / 函数 动态 * @default true */ truncate?: number | false | true | (ctx: CellContext): number | boolean | undefined; sortingOptions?: Omit, "getSortedRowModel" | "onSortingChange"> | undefined; columnSizingOptions?: Omit | undefined; columnPinningOptions?: Omit | undefined; rowSelectionOptions?: Omit, "onRowSelectionChange"> | undefined; /** * 子行字段名,设置后启用树形模式 */ childrenKey?: string & {} | keyof T & string | undefined; /** * 树形缩进:number 每层缩进 px / string CSS 值 / 函数 动态返回 CSS * @default '1rem' */ indentSize?: string | number | (ctx: CellContext): string | undefined; /** * 树形模式下的默认展开行为,仅在未提供 expanded / expandedKeys 时生效。true 展开全部父级行,number 展开 depth 小于该值的父级行,函数按行与深度自定义 * @default false */ defaultExpanded?: number | false | true | (row: T, depth: number): boolean | undefined; expandedOptions?: Omit, "getExpandedRowModel" | "onExpandedChange"> | undefined; /** * @default false */ expandOnRowClick?: boolean | undefined; /** * @default false */ selectOnRowClick?: boolean | undefined; /** * 可见列白名单(数组形) */ columnVisibilityKeys?: string[] | undefined; /** * 隐藏列黑名单(数组形),与 columnVisibilityKeys 互斥,同传时白名单优先 */ columnVisibilityExcludeKeys?: string[] | undefined; /** * 选中行 id 列表(数组形) */ rowSelectionKeys?: string[] | undefined; /** * 展开行 id 列表(数组形) */ expandedKeys?: string[] | undefined; onSelect?: (e: Event, row: TableRow): void | undefined; onHover?: (e: Event, row: TableRow | null): void | undefined; onRowContextmenu?: (e: Event, row: TableRow): void | ((e: Event, row: TableRow) => void)[] | undefined; /** * 分页配置,透传给 TanStack / UTable * - 客户端分页:传入即启用,自动注入 getPaginationRowModel * - 服务端分页:manualPagination=true 并提供 rowCount 或 pageCount */ paginationOptions?: Omit | undefined; /** * 粘性表头 * @default true */ sticky?: boolean | "header" | "footer" | undefined; paginationUi?: DataTablePaginationUi & { ui?: { root?: SlotClass; summary?: SlotClass; summaryText?: SlotClass; selectedCount?: SlotClass; actions?: SlotClass; pageSizeSelect?: SlotClass; pagination?: SlotClass; } | undefined; } | undefined; /** * 触底加载回调,传入即启用无限滚动模式(自动隐藏内置分页、async 期间派生 loading) */ loadMore?: (): void | Promise | undefined; /** * `loadMore` 返回的 Promise 被拒绝时调用;缺省时输出到控制台 */ onLoadMoreError?: (error: unknown): void | undefined; /** * 是否还能加载更多 * @default true */ canLoadMore?: boolean | undefined; /** * 触发 loadMore 的距底像素阈值 * @default 100 */ loadMoreDistance?: number | undefined; ui?: Record & { wrapper?: SlotClass; toolbar?: SlotClass; skeleton?: SlotClass; skeletonRow?: SlotClass; base?: SlotClass; tbody?: SlotClass; th?: SlotClass; td?: SlotClass; root?: SlotClass; caption?: SlotClass; thead?: SlotClass; tfoot?: SlotClass; tr?: SlotClass; separator?: SlotClass; empty?: SlotClass; loading?: SlotClass; } | undefined; /** * The element or component this component should render as. * @default 'div' */ as?: any; data?: readonly T[] | undefined; caption?: string | undefined; /** * Enable virtualization for large datasets. * Note: row pinning is not supported when virtualization is enabled. * @default false */ virtualize?: boolean | (Partial, "count" | "estimateSize" | "overscan">> & { getScrollElement?: (() => Element | null) | undefined; overscan?: number | undefined; estimateSize?: number | ((index: number) => number) | undefined; }) | undefined; /** * The text to display when the table is empty. * @default t('table.noData') */ empty?: string | undefined; /** * @default 'primary' */ loadingColor?: "primary" | "secondary" | "info" | "success" | "warning" | "error" | "important" | "neutral" | undefined; /** * @default 'carousel' */ loadingAnimation?: "carousel" | "carousel-inverse" | "swing" | "elastic" | undefined; /** * Use the `watchOptions` prop to customize reactivity (for ex: disable deep watching for changes in your data or limiting the max traversal depth). This can improve performance by reducing unnecessary re-renders, but it should be used with caution as it may lead to unexpected behavior if not managed properly. * @default { deep: true } */ watchOptions?: WatchOptions | undefined; globalFilterOptions?: Omit, "onGlobalFilterChange"> | undefined; columnFiltersOptions?: Omit, "getFilteredRowModel" | "onColumnFiltersChange"> | undefined; visibilityOptions?: Omit | undefined; groupingOptions?: Omit | undefined; rowPinningOptions?: Omit, "onRowPinningChange"> | undefined; facetedOptions?: FacetedOptions | undefined; state?: Partial | undefined; onStateChange?: (updater: Updater): void | undefined; renderFallbackValue?: any; /** * An array of extra features that you can add to the table instance. */ _features?: TableFeature[] | undefined; /** * Set this option to override any of the `autoReset...` feature options. */ autoResetAll?: boolean | undefined; /** * Set this option to `true` to output all debugging information to the console. */ debugAll?: boolean | undefined; /** * Set this option to `true` to output cell debugging information to the console. */ debugCells?: boolean | undefined; /** * Set this option to `true` to output column debugging information to the console. */ debugColumns?: boolean | undefined; /** * Set this option to `true` to output header debugging information to the console. */ debugHeaders?: boolean | undefined; /** * Set this option to `true` to output row debugging information to the console. */ debugRows?: boolean | undefined; /** * Set this option to `true` to output table debugging information to the console. */ debugTable?: boolean | undefined; /** * Default column options to use for all column defs supplied to the table. */ defaultColumn?: Partial & StringHeaderIdentifier> | Partial & IdIdentifier> | Partial & StringHeaderIdentifier> | Partial & IdIdentifier> | Partial & Partial> | Partial & Partial>> | Partial & StringHeaderIdentifier> | Partial & IdIdentifier> | undefined; /** * This optional function is used to derive a unique ID for any given row. If not provided the rows index is used (nested rows join together with `.` using their grandparents' index eg. `index.index.index`). If you need to identify individual rows that are originating from any server-side operations, it's suggested you use this function to return an ID that makes sense regardless of network IO/ambiguity eg. a userId, taskId, database ID field, etc. */ getRowId?: (originalRow: T, index: number, parent?: Row | undefined): string | undefined; /** * This optional function is used to access the sub rows for any given row. If you are using nested rows, you will need to use this function to return the sub rows object (or undefined) from the row. */ getSubRows?: (originalRow: T, index: number): T[] | undefined | undefined; /** * Use this option to optionally pass initial state to the table. This state will be used when resetting various table states either automatically by the table (eg. `options.autoResetPageIndex`) or via functions like `table.resetRowSelection()`. Most reset function allow you optionally pass a flag to reset to a blank/default state instead of the initial state. * * Table state will not be reset when this object changes, which also means that the initial state object does not need to be stable. */ initialState?: InitialTableState | undefined; /** * This option is used to optionally implement the merging of table options. */ mergeOptions?: (defaultOptions: TableOptions, options: Partial>): TableOptions | undefined; cellpadding?: string | number | undefined; cellspacing?: string | number | undefined; summary?: string | undefined; width?: string | number | undefined; pagination?: PaginationState | undefined; columnVisibility?: VisibilityState | undefined; columnPinning?: ColumnPinningState | undefined; columnSizing?: ColumnSizingState | undefined; rowSelection?: RowSelectionState | undefined; /** * @default { top: [], bottom: [] } */ rowPinning?: RowPinningState | undefined; /** * @default [] */ sorting?: SortingState | undefined; columnOrder?: ColumnOrderState | undefined; expanded?: true | Record | undefined; } ``` ### Emits ```ts /** * Emitted events for the MDataTable component */ interface MDataTableEmits { update:pagination: (payload: [value: PaginationState | undefined]) => void; update:columnVisibility: (payload: [value: VisibilityState | undefined]) => void; update:columnPinning: (payload: [value: ColumnPinningState | undefined]) => void; update:columnSizing: (payload: [value: ColumnSizingState | undefined]) => void; update:rowSelection: (payload: [value: RowSelectionState | undefined]) => void; update:rowPinning: (payload: [value: RowPinningState]) => void; update:sorting: (payload: [value: SortingState]) => void; update:columnOrder: (payload: [value: ColumnOrderState | undefined]) => void; update:expanded: (payload: [value: ExpandedState | undefined]) => void; update:columnVisibilityKeys: (payload: [value: string[] | undefined]) => void; update:columnVisibilityExcludeKeys: (payload: [value: string[] | undefined]) => void; update:rowSelectionKeys: (payload: [value: string[] | undefined]) => void; update:expandedKeys: (payload: [value: string[] | undefined]) => void; } ``` ### Slots ```ts /** * Slots for the MDataTable component */ interface MDataTableSlots { expanded(): any; empty(): any; loading(): any; caption(): any; body-top(): any; body-bottom(): any; pagination(): any; pagination-summary(): any; pagination-actions(): any; /** * 表格上方工具栏;开启 `columnSettings` 时默认渲染列设置按钮 */ toolbar(): any; } ``` Besides the named slots above, dynamic slots named after column ids are supported: `#-header`, `#-cell` and `#-footer`. See [Columns · Header and Cell Slots](https://nuxt.mhaibaraai.me/en/docs/data-table/columns#header-and-cell-slots). ### Expose Access the typed component instance (`DataTableExposed`) via [`useTemplateRef`](https://vuejs.org/api/composition-api-helpers.html#usetemplateref). | Name | Type | | --- | --- | | `tableRef` | `HTMLTableElement \| null`
Native table element | | `tableApi` | `Table \| null`
TanStack Table instance | | `el` | `HTMLElement \| null`
UTable root element (scroll container) | | `scrollToTop(options?)` | `void`
Scroll to top | | `clearSelection()` | `void`
Clear row selection | | `expandToDepth(depth)` | `void`
Expand to specified depth, `depth=0` collapses all | | `collapseAll()` | `void`
Collapse all rows | | `treeSelection` | `TreeSelectionResult`
Tree selection state: `selected`, `leaves`, `parents`, `halfSelected`, `strictlyChecked` | ### Column Types Each item in the `columns` array is a `DataTableColumn`, differentiated by shape: | Type | Matcher | Description | | --- | --- | --- | | `DataTableDataColumn` | Has `accessorKey` | Data column: sorting, pinning, truncation, tooltip, visibility, custom rendering | | `DataTableGroupColumn` | Has `children` | Group header | | `DataTableSelectionColumn` | `type: 'selection'` | Selection column (single/multi select, tree strategy) | | `DataTableIndexColumn` | `type: 'index'` | Index column | | `DataTableExpandColumn` | `type: 'expand'` | Expand column | | `DataTableRowPinningColumn` | `type: 'row-pinning'` | Row pinning column | | `DataTableActionsColumn` | `type: 'actions'` | Actions column | ### Event Handler Types Event handlers use the following types, with parameters inferred via contextual typing: | Type | Target Event | | --- | --- | | `DataTableSelectHandler` | `@select` | | `DataTableHoverHandler` | `@hover` | | `DataTableContextmenuHandler` | `@row-contextmenu` | ## Theme ::component-theme{slug="DataTable"} :: ## Changelog See commit history for [src/runtime/components/Introduction.vue](https://github.com/mhaibaraai/movk-nuxt/commits/main/src/runtime/components/Introduction.vue). # Appearance > Component style overrides, pagination style overrides, stripe and borders, visual density, fit-content width, empty-cell placeholders and sticky header. ## `ui` Component Style Overrides The `ui` prop accepts a slot-class map that deep-merges with the theme, allowing you to customize `root`, `th`, `td`, `tbody` and other partial styles: ```vue [DataTableUiOverrideExample.vue] ``` ## `paginationUi` Pagination Style Overrides `paginationUi.ui` accepts Pagination theme slots and can override `root`, `summary`, `actions`, `selectedCount` and other partial classes. `paginationUi` also supports configuring `show` and `pageSizes`: ```vue [DataTablePaginationUiExample.vue] ``` ## Stripe and Borders `stripe` controls the background color of even rows; `bordered` supports both boolean and object forms — the object form lets you customize vertical borders via `color`, `width` and `style`: ```vue [DataTableStripeBorderedExample.vue] ``` ## `density` Visual Density `density` switches between three cell-padding presets: `compact`, `normal` and `comfortable`: ```vue [DataTableDensityExample.vue] ``` ## `fitContent` Fit-Content Width `fitContent` makes the table width determined by column widths rather than stretching to fill the parent container — suitable for compact utility tables: ```vue [DataTableFitContentExample.vue] ``` ## `emptyCell` Empty-Value Placeholder `emptyCell` supports a string, a function template (returning a VNode) and `false`, respectively for custom text, a custom node and disabling the placeholder entirely. A per-column `emptyCell` takes precedence over the global setting: ```vue [DataTableEmptyCellVariantsExample.vue] ``` ## `sticky` Sticky Header `sticky` is enabled by default; disabling it makes the header scroll with the content. It requires a scroll container with a constrained height (e.g. `ui.root: 'max-h-[40vh]'`): ```vue [DataTableStickyExample.vue] ``` # Columns > Data column configuration — fixed columns, sorting, column pinning, column resize, text truncation, tooltips, visibility and functional per-column configuration. ## `fixed` Fixed Columns `column.fixed` pins a column to either side of the table, keeping it visible during horizontal scrolling: ```vue [DataTableFixedExample.vue] ``` ## `children` Grouped Headers Define grouped columns (`DataTableGroupColumn`) using `children` to create multi-level headers: ```vue [DataTableGroupExample.vue] ``` ## `sortable` Column Sorting The global `sortable` enables click-to-sort on all data column headers; a per-column `sortable` overrides the global setting in the opposite direction (e.g. `sortable: false` locks a column as non-sortable): ```vue [DataTableSortableExample.vue] ``` ## `pinable` Column Pinning The global `pinable` lets users click the pin icon on a header to cycle through `left`, `right` and `none`; a per-column `pinable` has higher priority and can force a fixed position: ```vue [DataTablePinableExample.vue] ``` ## `resizable` Column Resize The global `resizable` adds a drag handle to all data columns; `resizable: false` on a column locks its width. `columnResizeMode` controls whether reflow happens `onChange` (live during drag) or `onEnd` (after release): ```vue [DataTableResizableExample.vue] ``` ## `size` / `minSize` / `maxSize` Column Width `size` sets a fixed column width (a number or a preset `xs`–`xl`). When `size` is not set and only `minSize` / `maxSize` are provided, the column width adapts to content: `minSize` is the lower bound for auto-sizing and dragging; `maxSize` is the maximum draggable width. A column with `size` set is constrained in both directions by `minSize` / `maxSize`. ```ts const columns: DataTableColumn[] = [ { accessorKey: 'name', header: 'Name', minSize: 120 }, // auto, min 120 { accessorKey: 'bio', header: 'Bio', maxSize: 240 }, // auto, drag max 240 { accessorKey: 'id', header: 'ID', size: 'sm' } // fixed preset width 120 ] ``` > [!NOTE] > > The table uses > > table-layout: auto > > and stretches to fill the container; auto-sized column content may exceed > > maxSize > > (auto layout ignores cell > > max-width > > ). Therefore > > maxSize > > on an auto-sized column only constrains the drag upper limit. Use > > size > > to strictly fix a column width. > [!NOTE] > > Fixed columns ( > > fixed > > ) require a known width to participate in sticky offset calculations, so they default to > > size > > . Only when a side has a single fixed column (the innermost fixed column closest to the scroll area) can that column auto-size to content — set > > minSize > > / > > maxSize > > to allow it to stretch (a typical example is the sole actions column on the right). ## Text Truncation and Tooltip `truncate` controls pure truncation (`true` for single-line / `number` for multi-line / `false` to disable / a function for dynamic behavior); `tooltip` applies the same number of truncation lines and shows the full content in a float when it overflows. You do not need to configure both: ```vue [DataTableTruncateExample.vue] ``` ## Column Visibility `column.visibility` sets the default show/hide state; `columnVisibilityKeys` (allowlist) and `columnVisibilityExcludeKeys` (blocklist) are mutually exclusive — when both are provided the allowlist takes precedence: ```vue [DataTableVisibilityExample.vue] ``` ## `columnSettings` Column Settings Enable column settings to change visibility and order. `persistKey` stores column settings and page size in the browser. Use `v-model:columnOrder` to control order externally and `resetColumns()` to restore column defaults. ```vue [DataTableColumnSettingsExample.vue] ``` ## Functional Configuration `sortable`, `pinable` and `resizable` accept `(col) => boolean`; `truncate` and `tooltip` accept `(ctx) => boolean | number`. A single declaration replaces per-column booleans and can make dynamic decisions based on the field or cell context: ```vue [DataTableFunctionalExample.vue] ``` > [!TIP] > > Per-column props always take precedence over global props. The recommended pattern is "global on + individual off" or "global off + individual on" to express the difference. ## Header and Cell Slots Besides configuring `header` / `cell` in `columns`, you can render a column through slots named after its id. The id of a data column is its `accessorKey`; special columns use `__selection`, `__index`, `__expand`, `__row_pinning` and `__actions`: | Slot | Scope type | Description | | --- | --- | --- | | `#-header` | `HeaderContext` | Replaces the column header label | | `#-cell` | `CellContext` | Replaces the column cell content | | `#-footer` | `HeaderContext` | Replaces the column footer content | ```vue [DataTableColumnSlotsExample.vue] ``` > [!NOTE] > > #-header > > only replaces the > > label > > . The sort button, pin button and resize handle generated by > > sortable > > , > > pinable > > and > > resizable > > stay in the header, so you never have to render them yourself. > [!WARNING] > > #-cell > > replaces the whole cell content, so > > truncate > > , > > tooltip > > and > > emptyCell > > no longer apply to that column — handle them inside the slot when needed. Grouped headers ( > > children > > ) get an id assembled by TanStack internally and cannot be overridden by slots; use the > > header > > option instead. # Special Columns > Configuration for selection, index, row-pinning and actions columns — including tree selection strategies, dynamic button props and confirmation dialogs. ## Overview Data columns bind fields via `accessorKey`; special columns are distinguished by `type` and do not need an `accessorKey`: | `type` | Purpose | | --- | --- | | `selection` | Row selection (single/multiple, tree cascade strategies) | | `index` | Row index | | `expand` | Tree expansion (see [Tree Data](https://nuxt.mhaibaraai.me/en/docs/data-table/tree)) | | `row-pinning` | Pin rows to top or bottom | | `actions` | Row action buttons | > [!TIP] > > All special columns also support > > visibility > > , > > pinable > > , > > resizable > > , > > fixed > > , > > size > > , > > align > > . ## Selection Column ### `mode` Single / Multiple How `mode` works: the default `multiple` automatically renders header and cell checkboxes and syncs the selected-id dictionary via `v-model:row-selection`; `single` disables multi-select, shows a custom `header`, and keeps at most one selected row at all times: ```vue [DataTableSelectionExample.vue] ``` ### `strategy` Tree Selection Strategy `strategy` takes effect in tree mode (`children-key`) and controls the parent–child check relationship: `cascade` for parent–child cascade, `isolated` for independent selection, `leaf` for leaf-only selection (parent nodes show a derived state): ```vue [DataTableSelectionStrategyExample.vue] ``` ### `checkboxProps` Functional Configuration `checkboxProps` receives context and returns props: you can distinguish header/cell by `scope`, parent row derived state by `isLeafAggregate`, and derive `disabled` from row data: ```vue [DataTableSelectionCheckboxPropsExample.vue] ``` ### rowSelectionKeys and treeSelection `v-model:row-selection-keys` provides external controlled state in array form; the component-exposed `treeSelection` derives business views such as `leaves`, `parents`, `halfSelected` and `strictlyChecked` (accessible via `useTemplateRef`): ```vue [DataTableSelectionKeysExample.vue] ``` ## Index Column `type: 'index'` renders a `#` header by default; the row number is automatically recalculated with sorting and pagination, and can be customized via `header`: ```vue [DataTableIndexExample.vue] ``` ## Row Pinning Column ### `position` Pin to Top / Bottom The `position` prop of `type: 'row-pinning'` takes `top` or `bottom`, pinning rows to the header or footer. `v-model:row-pinning` exposes two id groups: `top` and `bottom`: ```vue [DataTableRowPinningExample.vue] ``` ### `buttonProps` Dynamic Pin Button `buttonProps` receives the `pinned` state and returns `icon`, `color` and `variant`, distinguishing pinned from unpinned rows: ```vue [DataTableRowPinningDynamicExample.vue] ``` ## Actions Column ### `maxInline` Inline and Overflow `maxInline` controls the number of inline buttons; extras collapse into an overflow menu. `action.divider` inserts a separator in the menu: ```vue [DataTableActionsInlineExample.vue] ``` ### `actions` Array and Functional `actions` accepts either a static array or a `(ctx) => DataTableAction[]` function to derive actions per row: ```vue [DataTableActionsFunctionalExample.vue] ``` ### Async Action Auto Loading When `onClick` returns a Promise, the button automatically enters a loading state and is disabled to prevent re-triggering (inline buttons only): ```vue [DataTableActionsAsyncExample.vue] ``` ### `confirm` Confirmation Dialog `confirm: true` pops up a MessageBox before executing; `confirmProps` can dynamically return `title`, `type`, `description` and `confirmLabel`: ```vue [DataTableActionsConfirmExample.vue] ``` ### Dynamic `disabled` and `visibility` `action.disabled` and `action.visibility` accept a boolean or `(ctx) => boolean` to derive disabled or hidden state per row: ```vue [DataTableActionsDynamicStateExample.vue] ``` ## Shared Fields for Special Columns `selection`, `index`, `row-pinning` and `actions` columns support the same `visibility`, `pinable`, `resizable`, `size`, `minSize`, `maxSize`, `align` and `fixed` as data columns. Special columns default to a fixed width of 60; providing `minSize` / `maxSize` (without `size`) switches them to auto-sizing — `minSize` is the lower bound and `maxSize` is the drag upper limit. The sole right-side actions column (`fixed: 'right'`) can set `minSize` to expand with the number of buttons. See [Data Column Width Rules](https://nuxt.mhaibaraai.me/en/docs/data-table/columns) for details. ```vue [DataTableSpecialSharedExample.vue] ``` # Rows & Interaction > Row selection, expandable detail slot, click behaviors, dynamic row class/style, hover, context menu and imperative control. ## `rowKey` Row Identifier `row-key` specifies the unique identifier field for a row and automatically derives TanStack's `getRowId`. It is the foundation for selection, expansion, tree data and other features to correctly track rows. Once set, selection and expansion state are tracked by the business id rather than the array index — reordering `data` keeps the selected rows pointing to the same records: ```vue [DataTableRowKeyExample.vue] ``` ## Basic Row Selection `v-model:row-selection` bi-directionally syncs the selected id set; the `@select` event returns the currently clicked row (`DataTableSelectHandler`): ```vue [DataTableRowSelectionExample.vue] ``` ## Row Expansion and Detail Slot `v-model:expanded` controls expanded row ids; the `#expanded` slot renders the detail area: > [!NOTE] > > The > > type: 'expand' > > column header renders an "expand all / collapse all" button by default — disable it with > > toggleAll: false ```vue [DataTableRowExpandExample.vue] ``` ## Row Click for Selection and Expansion `select-on-row-click` toggles selection on a full-row click; `expand-on-row-click` toggles expansion on a full-row click. Both can be enabled independently: ```vue [DataTableRowClickExample.vue] ``` ## Dynamic Row Styles `row-class` accepts `(row) => string`; `row-style` accepts `(row) => string | Record` to derive class names and inline styles from row data: ```vue [DataTableRowStyleExample.vue] ``` ## Row Hover Tracking `@hover` fires on row enter and leave (`DataTableHoverHandler`); the second argument is a `TableRow` or `null`, useful for syncing external highlights: ```vue [DataTableRowHoverExample.vue] ``` ## Row Context Menu `@row-contextmenu` intercepts right-click events (`DataTableContextmenuHandler`); the callback receives the original `MouseEvent` and the target row, allowing you to prevent the default menu and show a custom one: ```vue [DataTableRowContextmenuExample.vue] ``` ## Imperative Control Obtain the component instance via `useTemplateRef` and call the exposed `clearSelection()` to clear selection or `scrollToTop()` to scroll back to the top: ```vue [DataTableRowImperativeExample.vue] ``` # Tree Data > Enable tree-mode tables via childrenKey — configure expansion, cascade selection strategies, indentation and read selection results. ## Tree Data Basics Setting `children-key` enables tree mode. Combine with `row-key` to derive row ids and an `expand` column to render collapse buttons. Missing fields on parent rows (e.g. level) can be filled by `emptyCell`: ```vue [DataTableTreeBasicExample.vue] ``` ## `strategy` Cascade Selection Strategy The `strategy` of the `selection` column determines parent–child check synchronization: `cascade` for parent–child cascade, `isolated` for independent selection, `leaf` for leaf-only selection (parent nodes show a derived state from their descendants): ```vue [DataTableTreeStrategyExample.vue] ``` ## `mode` Single and Multiple Selection With `mode: 'single'`, the entire tree allows only one row to be checked at a time (usually paired with `isolated`); with `multiple`, the `strategy` drives the cascade behavior: ```vue [DataTableTreeModeExample.vue] ``` ## Reading Selection Results `v-model:row-selection-keys` bi-directionally syncs the selected id array; the component-exposed `treeSelection` derives four business views — `leaves`, `parents`, `halfSelected` and `strictlyChecked` — and provides `clearSelection()`: ```vue [DataTableTreeResultExample.vue] ``` ## `indentSize` Tree Indentation `indentSize` supports string, number (px) and function forms; the function form can dynamically adjust based on `row.depth` and other context: ```vue [DataTableTreeIndentExample.vue] ``` ## `defaultExpanded` Default Expansion `default-expanded` determines the initial expansion state when neither `expanded` nor `expanded-keys` (controlled mode takes priority) is provided: `true` expands all parent rows; a `number` expands parent rows whose `depth` is less than that value (equivalent to `expandToDepth(n)`); a function `(row, depth) => boolean` customizes expansion per row and depth, without having to manually collect parent ids: ```vue [DataTableTreeDefaultExpandExample.vue] ``` ## Expansion Behavior Control The `expand` column's `buttonProps` and `toggleAllButtonProps` customize the cell and header buttons respectively (receiving `isExpanded` / `isAllExpanded`); `expand-on-row-click` triggers expansion on a full-row click; the exposed `expandToDepth(n)` expands by layer and `collapseAll()` collapses everything; `v-model:expanded-keys` syncs the expanded id array: ```vue [DataTableTreeExpandExample.vue] ``` # Pagination & Load More > Client-side auto pagination, server-side manual pagination with loading state, and bottom-trigger load-more for infinite scroll. ## CSV Export `exportCsv()` exports loaded filtered and sorted rows. Use `rows: 'page'` for visible rows on the current page, or `rows: 'selected'` for loaded selected rows. To export all matching server rows, provide `serverCsvExport` and call `await table.exportServerCsv()`. The callback receives column IDs, filename, sorting and filters. Combine these with external filters before calling the backend. Use `useDownloadWithProgress` in Nuxt or supply a download function in plain Vue. With loading enabled and no data, `skeletonRows` controls the number of placeholders and defaults to 5. The `loading` slot takes priority. ## Client-Side Auto Pagination Passing `v-model:pagination` triggers automatic client-side pagination; the component slices the data locally and renders the default pagination bar: ```vue [DataTableClientPaginationExample.vue] ``` ## Server-Side Manual Pagination Set `paginationOptions.manualPagination` to `true` and provide `rowCount` to hand off pagination to the caller — pass only the current page's data via `data`. The example below uses local slicing to simulate a server; in a real scenario you should request the backend whenever `pagination` changes: ```vue [DataTableServerPaginationExample.vue] ``` > [!TIP] > > Combine > > :loading > > , > > :sorting-options="{ manualSorting: true }" > > and > > v-model:sorting > > for server-side sorting; reset > > pagination.pageIndex > > to 0 when a search is triggered. ## Page-Count Mode When the backend returns only the total page count rather than total rows, use `paginationOptions.pageCount` to specify the total pages directly: ```vue [DataTablePageCountPaginationExample.vue] ``` ## Page Size Switching When `paginationUi.pageSizes` has more than one item, a page-size switcher is shown: ```vue [DataTablePageSizesPaginationExample.vue] ``` ## Pagination Summary and Labels `v-model:row-selection` combined with `row-key` syncs the selected count; `paginationUi`'s `showSelectedCount`, `showRowRange` and `text` control the summary area's display and labels: ```vue [DataTablePaginationSummaryExample.vue] ``` ## Passing Props to the Pagination Component `paginationUi.paginationProps` passes through `UPagination` props such as `showEdges` and `siblingCount`; `pageSizeSelectProps` passes through page-size selector props: ```vue [DataTablePaginationPassthroughExample.vue] ``` ## Pagination Slots `#pagination-summary` and `#pagination-actions` replace the summary area and actions area respectively: ```vue [DataTablePaginationSlotsExample.vue] ``` The `#pagination` slot receives the full pagination state (`page`, `pageCount`, `from`, `to`, `setPage`, etc.) and replaces the entire default pagination bar: ```vue [DataTablePaginationFullExample.vue] ``` ## `loading` Loading State `loading` is passed through to the underlying `UTable` to display a loading indicator, suitable for initial data fetch or page-turn waits: ```vue [DataTableLoadingExample.vue] ``` ## `loadMore` Bottom-Triggered Load Passing a `load-more` callback enables infinite scroll mode (the built-in pagination bar is automatically hidden). When the callback returns a Promise, the component automatically derives `loading` during the load: ```vue [DataTableLoadMoreExample.vue] ``` > [!NOTE] > > A scroll container with a constrained height (e.g. > > ui.root: 'h-[60vh]' > > ) is required to produce scrolling and trigger the bottom-load callback. ## `canLoadMore` Stop Loading When `can-load-more` is `false`, triggering stops — you can force a pause independently of remaining data (e.g. no more data, or stop after an error): ```vue [DataTableLoadMoreCanLoadMoreExample.vue] ``` ## `loadMoreDistance` Trigger Threshold `load-more-distance` sets the distance-from-bottom threshold in pixels (default 100) — a larger value triggers loading earlier: ```vue [DataTableLoadMoreDistanceExample.vue] ``` ## Caller-Managed Loading If you want the caller to manage loading state, make `load-more` return synchronously (without handing back a Promise) and pass `:loading` manually, in contrast to the auto-derived form: ```vue [DataTableLoadMoreManualLoadingExample.vue] ``` # Overview > Nuxt data-fetching fundamentals and the core concepts and architecture of the Movk Nuxt API system. ## Nuxt Data Fetching Fundamentals Nuxt provides three data-fetching approaches. Understanding the differences helps you choose the right Movk Nuxt wrapper. - [`$fetch`](https://nuxt.com/docs/4.x/api/utils/dollarfetch): The low-level HTTP client, based on [ofetch](https://github.com/unjs/ofetch), usable on both server and client.```ts // Called on user interaction — use $fetch async function handleSubmit() { const result = await $fetch('/api/login', { method: 'POST', body: { username, password } }) } ``` - [`useFetch`](https://nuxt.com/docs/4.x/api/composables/use-fetch): A syntactic sugar wrapper around `useAsyncData` + `$fetch`.```ts // Fetch data on page load — use useFetch const { data: posts, status, error } = await useFetch('/api/posts') ``` - [`useAsyncData`](https://nuxt.com/docs/4.x/api/composables/use-async-data): The most flexible data-fetching composable.```ts // Aggregate multiple endpoints — use useAsyncData const { data } = await useAsyncData('dashboard', async () => { const [users, stats] = await Promise.all([ $fetch('/api/users'), $fetch('/api/stats') ]) return { users, stats } }) ``` ## Key Parameters Explained Three core parameters of `useFetch` (and `useApiFetch`) determine when and how requests are executed. ### `server` Controls whether data fetching is executed on the server. **Defaults to `true`.** **Behavior comparison:** - `server: true` (default) — During SSR the request is made on the server; data is transferred to the client via payload and not re-fetched on the client. - `server: false` — Executed on the client only. On first load, data starts fetching after hydration completes; `data` is initially `null`. **Use cases:** - `server: true` — SEO-relevant data, content required on first render. - `server: false` — Non-SEO-sensitive data (user comments, personalized recommendations, analytics), reducing server load. ```ts // Article list needs SEO — server: true (default) const { data: posts } = await useApiFetch('/posts') // Comment data doesn't need SSR — server: false const { data: comments } = useApiFetch('/comments', { server: false, lazy: true, }) ``` > [!NOTE] > > server: false > > is typically paired with > > lazy: true > > , which is exactly the preset behavior of > > useClientApiFetch > > . ### `lazy` Controls whether client-side navigation is blocked. **Defaults to `false`.** **Behavior comparison:** - `lazy: false` (default) — Blocks navigation via Vue Suspense, waiting for data before completing the route transition. The user never sees a loading state. - `lazy: true` — Does not block navigation; the page displays immediately while data loads in the background. You must handle the loading state manually. **Use cases:** - `lazy: false` — Core page data without which the page cannot render correctly. - `lazy: true` — Secondary data, non-above-the-fold data, scenarios where a skeleton screen can be shown first. ```ts // Core data — block navigation and wait for data (default) const { data: article } = await useApiFetch

(`/articles/${id}`) // Secondary data — don't block navigation, load in background const { data: related, status } = useLazyApiFetch( `/articles/${id}/related` ) ``` ```vue ``` > [!NOTE] > > During SSR, > > lazy > > behaves nearly the same as non-lazy (both wait for data); the difference primarily applies during > > client-side navigation > > . ### `immediate` Controls whether the request fires immediately when the composable is initialized. **Defaults to `true`.** **Behavior comparison:** - `immediate: true` (default) — Triggers the request on creation. - `immediate: false` — No automatic request; `status` is `idle`. You must call `execute()` manually. **Use cases:** - `immediate: true` — Data needed as soon as the page loads. - `immediate: false` — Requests that should only be triggered after a user action. ```ts // Pre-define a form-submit request, don't auto-execute const { data, execute, status, error } = useApiFetch('/login', { method: 'POST', body: credentials, immediate: false, lazy: true, }) // Trigger manually when the user clicks the login button async function handleLogin() { await execute() if (!error.value) { navigateTo('/dashboard') } } ``` > [!TIP] > > immediate: false > > is commonly paired with > > lazy: true > > . If only > > immediate: false > > is set without > > lazy: true > > , Suspense will still wait (even though the request never fires), which may cause the page to hang. ## Movk Nuxt API System Movk Nuxt creates one ofetch-wrapping API client per endpoint (the [`$api` plugin](https://nuxt.mhaibaraai.me/en/docs/api/api-plugin)) and a set of composables that wrap `useFetch`, adding unified auth, business code checking, error normalization, Toast notifications and other enhancements on top of Nuxt's native data-fetching capabilities. ```text nuxt.config.ts (movk.api config) | v api.factory.ts plugin — creates and caches one $api client per endpoint | v Endpoint client (per call: built-in hooks first, then user hooks — never overridden) ├── onRequest: Auth injection -> debug logging -> movk:api:request hook ├── onResponse: Restore JSON read as stream -> business check -> data unwrap -> movk:api:response hook -> success Toast └── exit catch: Normalize to ApiError -> 401 handling -> movk:api:error hook -> error Toast (once, after retries) | v Composables ├── useApiFetch useFetch + $api (SSR/CSR universal) ├── useLazyApiFetch lazy: true preset ├── useClientApiFetch server: false, lazy: true preset ├── useUploadWithProgress $api pipeline + XHR adapter for upload progress ├── useDownloadWithProgress $api.raw streaming read + download progress └── useApiStream $api.stream() + SSE parsing + abort ``` Upload, download and streaming requests go through the same client pipeline as `useApiFetch`, so endpoint headers, auth, business checks, error classification and hooks are identical. Streaming responses (SSE, binary) never enter the business-check and unwrapping chain: as soon as `onResponse` detects a readable stream it short-circuits, handing over to [`useApiStream`](https://nuxt.mhaibaraai.me/en/docs/api/stream) or [`createChatTransport`](https://nuxt.mhaibaraai.me/en/docs/api/stream). ### Multi-Endpoint Support Multiple API endpoints can be configured, each with its own baseURL, auth, Toast and response rules. Switch endpoints with the `endpoint` option or `$api.use()`. > [!TIP] > See: /en/docs/getting-started/configuration#endpoints > > Learn about endpoint configuration options ### Automatic Authentication Integrates with `nuxt-auth-utils`. When enabled, each request automatically extracts the token from the session and injects it into the request headers. Supports nested paths (e.g. `user.accessToken`) and multiple token formats (Bearer, Basic, Custom). > [!TIP] > See: /en/docs/getting-started/configuration#auth > > Learn about authentication configuration options ### Business Status Code Check The `$api` interceptor automatically checks whether the response `code` is in `successCodes`, throwing an `ApiError` and showing a Toast on business failure. Endpoints returning bare resources can turn off `businessCheck` on their `response`. > [!TIP] > See: /en/docs/api/api-plugin#data-unwrapping-and-business-validation > > See interactive examples for business validation and > > businessCheck ### Data Unwrapping The `$api` interceptor automatically extracts the `dataKey` field (default `data`) from the response; the generic `T` directly maps to the business data type. > [!TIP] > See: /en/docs/api/api-plugin#data-unwrapping-and-business-validation > > See interactive examples for unwrapping and > > unwrap ### Error Normalization Every failure (business code, HTTP 4xx/5xx, network failure, timeout) becomes an `ApiError` (`NuxtError`), classified by `error.data.kind`; the `error` of `useApiFetch` is the very object thrown by `$api`. > [!TIP] > See: /en/docs/api/use-api-fetch#error-classification > > See the error classification example ### Toast Notifications Success/failure Toasts are shown automatically. Supports four levels of configuration priority: request-level > endpoint-level > global-level > built-in defaults. Can be disabled or customized at any level. > [!TIP] > See: /en/docs/getting-started/configuration#toast > > Learn about Toast configuration options ### 401 Unauthorized Handling When an HTTP 401 or a business code 401 is received (including upload / download progress requests), the default behavior clears the session and redirects to the login page. This can be intercepted via [API Hooks](https://nuxt.mhaibaraai.me/en/docs/api/hooks#movkapiunauthorized) to implement custom logic (e.g. token refresh). > [!TIP] > See: /en/docs/getting-started/configuration#auth > > Learn about 401 handling configuration options ## Migrating from v1 to v2 v2 consolidates response handling into one client per endpoint. The following changes require caller updates: | Change | v1 | v2 | | --- | --- | --- | | Per-request switches use positive names | `skipBusinessCheck: true` / `skipUnwrap: true` | `businessCheck: false` / `unwrap: false` | | `$api` per-request options are no longer wrapped in `context` | `$api(url, { context: { toast: false } })` | `$api(url, { toast: false })` | | Bare-resource endpoints are declared on the endpoint | Pass both skip switches on every request | `endpoints.x.response: { businessCheck: false, unwrap: false }` | | Every failure is an `ApiError` (NuxtError) | `error.isBusinessError`, `error.response`; HTTP / network errors are `FetchError` | `error.data.kind === 'business'`, `error.data.response`; HTTP, network and timeout errors are `ApiError` too | | `movk:api:error` gains an error argument and fires once | `(context)`, fires twice on GET 5xx retries, never on network errors | `(context, error)`, fires once after retries, including network errors and timeouts | | Upload timeout option renamed | `timeoutMs` | `timeout` | | Upload / download headers layer the same way as `$api` | User `headers` override the auth header, endpoint `publicHeaders` ignored | Endpoint `publicHeaders` are injected; with auth enabled the auth header is written last and wins | | Upload / download still unwrap with checking off | `skipBusinessCheck` returns the raw body | `businessCheck: false` still unwraps by `dataKey`; add `unwrap: false` for the raw body | User `onRequest` / `onResponse` hooks passed to `$api` no longer replace the built-in interceptors; v1 code that relied on overriding them to bypass unwrapping should use `unwrap: false` instead. # $api > The enhanced $fetch instance created by the api.factory plugin, supporting auth injection, data unwrapping, business code checking and multi-endpoint switching. ## Introduction `$api` is a global `$fetch` instance injected by a Nuxt plugin, with a full built-in interceptor chain (auth injection, business status code checking, data unwrapping, Toast notifications). It is the underlying engine for all API composables (`useApiFetch`, `useLazyApiFetch`, etc.). ## Usage ```ts const { $api } = useNuxtApp() // GET request (data is automatically unwrapped) const users = await $api('/users') // POST request const user = await $api('/users', { method: 'POST', body: { name: 'test', email: 'test@example.com' } }) // PUT request const updated = await $api(`/users/${id}`, { method: 'PUT', body: { name: 'new-name' } }) // DELETE request await $api(`/users/${id}`, { method: 'DELETE' }) ``` > [!NOTE] > > Data returned by > > $api > > has already been automatically unwrapped by the interceptor (the > > dataKey > > field is extracted); the generic > > T > > directly maps to the business data type. ## Multi-Endpoint Switching Use `$api.use(endpoint)` to switch to a specific endpoint: ```ts const { $api } = useNuxtApp() // Use the default endpoint const users = await $api('/users') // Switch to the admin endpoint const adminUsers = await $api.use('admin')('/users') // Save an endpoint reference to avoid repeated use() calls const adminApi = $api.use('admin') const config = await adminApi('/config') const stats = await adminApi('/stats') ``` Endpoint instances are internally cached, so multiple calls to `$api.use('admin')` return the same instance. ### Switch and Compare baseURL `$api` uses the `baseURL` of the default endpoint; calling `$api.use(name)` switches to the named endpoint's `baseURL`. Select a different endpoint in the dropdown to observe the baseURL and response change accordingly: ```vue [ApiEndpointsExample.vue] ``` ### Imperative Usage Outside a `useFetch` context, obtain an endpoint instance via `$api.use(name)` and make raw requests directly: ```vue [ApiEndpointsImperativeExample.vue] ``` ### Active Runtime Config `runtimeConfig.public.movkApi` exposes the endpoint list and default endpoint name for runtime debugging: ```vue [ApiEndpointsRuntimeExample.vue] ``` > [!TIP] > See: /en/docs/getting-started/configuration#endpoints > > Learn how to configure multiple API endpoints ## Auth Integration When `auth` is enabled and `tokenSource` is `'session'` (default), the module automatically integrates with `nuxt-auth-utils`: after login it reads the token from `session[sessionTokenPath]` and all `$api` requests automatically inject the `Authorization` header. On a 401 response, the `auth.unauthorized` strategy clears the session or redirects to the login page. ### Current Session The reactive session exposed by `useUserSession`; call `fetch()` after login/logout to sync state: ```vue [ApiAuthSessionExample.vue] ``` ### Calling a Protected Endpoint `useApiFetch` automatically carries the Authorization header when accessing `/demo/protected`; returns 401 when not logged in: ```vue [ApiAuthProtectedExample.vue] ``` ### 401 Handling Strategy `auth.unauthorized` controls redirect and session clearing; this docs site disables redirect for demonstration purposes: ```vue [ApiAuthUnauthorizedExample.vue] ``` ### Token Injection Format `headerName` + `tokenType` determine the final request header format; the backend echoes the `authHeader` field for verification: ```vue [ApiAuthTokenInjectionExample.vue] ``` ## Data Unwrapping and Business Validation `$api` extracts business data by `response.dataKey` and validates the business code against `successCodes` by default. The `unwrap` / `businessCheck` switches can be declared globally, per endpoint or per request, with precedence explicit request value > endpoint > global. Select a mode in the dropdown to observe the difference in the returned structure: - `default`: Extracts business data by the default `data` field; the caller receives the de-enveloped object directly. - `no-unwrap`: `unwrap: false` — does not overwrite `response._data`, preserving the full `code/message/data` envelope. - `no-business-check`: Legacy endpoints that don't return a `code` field — `businessCheck: false` disables validation and still unwraps the business data by `dataKey`. - `combined`: Non-standard external envelopes — disable both to let the caller handle the response entirely. ```vue [ApiUnwrapExample.vue] ``` ### Endpoint-Level Declaration Returning a bare array or object (no `{ code, data }` envelope) is an inherent property of an endpoint. Declare it once on the endpoint `response`, and every request to that endpoint (including upload, download and streaming) follows it: ```ts [nuxt.config.ts] export default defineNuxtConfig({ movk: { api: { endpoints: { sensor: { baseURL: process.env.NUXT_SENSOR_URL, response: { businessCheck: false, unwrap: false } } } } } }) ``` ```ts // Receives the array directly const points = await $api.use('sensor')('/point-numbers') // Explicit request values win: re-enable business-code checking for a single request await $api.use('sensor')('/legacy', { businessCheck: true }) ``` > [!NOTE] > > With checking enabled, a non-object response body ( > > null > > , string, array, etc.) is treated as a business failure ( > > error.data.kind > > is > > business > > ) instead of throwing a > > TypeError > > . ## Toast Notifications `$api` has built-in Toast notifications, determining success/failure by `toast.successCodes`. Supports two levels of customization: global defaults and per-request overrides. Select a mode in the dropdown and toggle the "inject error" switch to observe the success/failure branches: - `default`: No `toast` passed — inherits global config; both success and error use the default style. - `silent`: `toast: false` — disables all per-request notifications. - `message`: `successMessage` / `errorMessage` replace the default text. - `error-only`: `{ success: false }` — disables success notification but keeps error notification. - `custom`: Overrides `color`, `icon` and other ToastProps for success and error separately. > [!NOTE] > > Setting > > toast.success.methods > > in the global or endpoint config limits success notifications to mutating requests (POST / PUT / PATCH / DELETE). A single GET can still opt back in with request-level > > { success: { show: true } } > > or > > successMessage > > . ```vue [ApiToastExample.vue] ``` ## Using in Event Handlers Using `$api` inside event handlers is the most common scenario: ```vue ``` ## Using in useAsyncData When you need to aggregate multiple endpoints or do complex data processing, use `$api` inside `useAsyncData`: ```ts const { $api } = useNuxtApp() // Aggregate multiple endpoints const { data: dashboard } = await useAsyncData('dashboard', async () => { const [users, stats, recent] = await Promise.all([ $api('/users'), $api('/stats'), $api('/activity/recent') ]) return { users, stats, recent } }) ``` ### Wrapping a Custom Composable ```ts [app/composables/useDashboard.ts] export function useDashboard() { const { $api } = useNuxtApp() return useAsyncData('dashboard', async () => { const [users, stats] = await Promise.all([ $api('/users'), $api('/stats') ]) return { users, stats } }) } ``` ### Business Operation Composable For write operations such as delete or approve, encapsulate the `$api` calls in a dedicated composable to keep page files lean: ```ts [app/composables/useUserActions.ts] export function useUserActions() { const { $api } = useNuxtApp() async function remove(id: string) { await $api(`/users/${id}`, { method: 'DELETE' }) await refreshNuxtData() } async function create(data: CreateUserRequest) { return await $api('/users', { method: 'POST', body: data, }) } async function updateRole(id: string, role: UserRole) { return await $api(`/users/${id}/role`, { method: 'PUT', body: { role }, toast: { successMessage: 'Role updated' }, }) } return { remove, create, updateRole } } ``` ```vue [app/pages/users/index.vue] ``` ## Per-Request Configuration Per-request options sit at the same level as ofetch options; `$api`, `useApiFetch`, upload/download and streaming requests share the same shape: ```ts const { $api } = useNuxtApp() // Disable Toast await $api('/users', { toast: false }) // Custom Toast message await $api('/users', { method: 'POST', body: formData, toast: { successMessage: 'Created successfully' } }) // Disable business status code checking (still unwraps by dataKey) const data = await $api('/external-api/data', { businessCheck: false }) ``` User-provided hooks such as `onRequest` / `onResponse` run together with the built-in interceptors (built-in first) and never override auth, business validation, unwrapping or Toast: ```ts await $api('/users', { onResponse({ response }) { // response._data is already processed by the policy } }) ``` > [!NOTE] > > These options are declared through a type extension of ofetch's > > FetchOptions > > and are only recognized by Movk Nuxt's > > $api > > client; the native > > $fetch > > ignores them. ## Error Handling Every error thrown by `$api` is an `ApiError` (`NuxtError`), classified by `error.data.kind` as `business`, `http`, `network`, `timeout` or `aborted`. The error Toast and `movk:api:error` fire only once after ofetch retries finish; aborts are not reported: ```ts try { await $api('/orders', { method: 'POST', body }) } catch (error) { const { kind, code } = (error as ApiError).data ?? {} if (kind === 'business' && code === 40001) { // business-code branch } } ``` ## API ### ApiInstance Type definition of `$api`: ```ts type ApiInstance = $Fetch & { use: (endpoint: string) => ApiInstance stream: (url: string, options?: ApiStreamOptions) => Promise> } ``` **$api(url, options)** (`Promise`): Send an API request. Supports all ofetch options plus the fields of ApiRequestOptions. $api.raw returns the full response through the same pipeline. **$api.use(endpoint)** (`ApiInstance`): Switch to the specified endpoint and return that endpoint's $api instance. endpoint is typed as MovkApiEndpointName (a literal union merged by the module from the movk.api.endpoints declaration). Endpoint instances are internally cached; multiple calls return the same instance. ### ApiRequestOptions Per-request configuration passed alongside ofetch options: **toast** (`RequestToastOptions | false`): Toast configuration. Set to false to disable all Toast notifications; { success: { show: true } } re-enables it for one request when globally disabled. **businessCheck** (`boolean`): Whether to validate the business status code against successCodes. Inherits the endpoint / global response.businessCheck when omitted; when false, no business ApiError is thrown but the dataKey field is still unwrapped. **unwrap** (`boolean`): Whether to unwrap by dataKey. Inherits the endpoint / global response.unwrap when omitted; when false, the interceptor does not overwrite response._data and the caller receives the raw body. Orthogonal to businessCheck. ### ApiError ```ts type ApiError = NuxtError interface ApiErrorData { kind: 'business' | 'http' | 'network' | 'timeout' | 'aborted' endpoint: string code?: number | string response?: unknown } ``` **statusCode** (`number`): The HTTP status on HTTP failures; on business failures the business code when it falls within 100–599, otherwise 500. **message** (`string`): Error message, preferring the messageKey field of the response body. **data.kind** (`ApiErrorKind`): Error category: business failed business-code check, http HTTP 4xx/5xx, network no response received, timeout timed out, aborted aborted by the caller. **data.code** (`number | string`): The original business code (business) or HTTP status (http). **data.response** (`unknown`): The raw response body. # Hooks > Extend API system behavior via Nuxt runtime hooks — global request interception, error handling and custom 401 logic. ## Introduction The Movk Nuxt API system exposes 4 extension points via Nuxt runtime hooks, allowing you to extend and customize API behavior without modifying source code. All hook types are automatically registered into `RuntimeNuxtHooks` via module declaration; in your editor, `nuxtApp.hook('movk:api:')` provides full auto-completion. ## Available Hooks ### `movk:api:request` **When triggered**: After auth token injection, before the request is actually sent. ```ts 'movk:api:request': (context: FetchContext) => void | Promise ``` Typical use cases: Adding extra request headers, request logging, modifying request parameters. ```ts [plugins/api-logger.ts] export default defineNuxtPlugin((nuxtApp) => { nuxtApp.hook('movk:api:request', (context) => { console.log(`[API] ${context.options.method || 'GET'} ${context.request}`) }) }) ``` ### `movk:api:response` **When triggered**: After business status code validation passes and data unwrapping is complete. ```ts 'movk:api:response': ( context: FetchContext & { response: FetchResponse } ) => void | Promise ``` At this point, `context.response._data` is already the unwrapped business data. Typical use cases: Global data transformation, response logging, performance analysis. ```ts [plugins/api-analytics.ts] export default defineNuxtPlugin((nuxtApp) => { nuxtApp.hook('movk:api:response', (context) => { analytics.track('api_success', { url: context.request, method: context.options.method || 'GET' }) }) }) ``` ### `movk:api:error` **When triggered**: On business status code validation failure, HTTP error (4xx/5xx), network failure or timeout. Fires **only once**, after ofetch retries finish; aborts never fire it. For 401 errors, this fires after `movk:api:unauthorized` and is skipped when the business side handled it. ```ts 'movk:api:error': ( context: FetchContext, error: ApiError ) => void | Promise ``` `error` is the normalized [`ApiError`](https://nuxt.mhaibaraai.me/en/docs/api/api-plugin#apierror); `error.data` carries the category, endpoint, business code and raw response body. Typical use cases: Global error reporting (Sentry, etc.), error analytics. ```ts [plugins/error-reporter.ts] export default defineNuxtPlugin((nuxtApp) => { nuxtApp.hook('movk:api:error', (context, error) => { if (error.data?.kind === 'network') return Sentry.captureException(error, { extra: { url: context.request, endpoint: error.data?.endpoint, response: error.data?.response } }) }) }) ``` ### `movk:api:unauthorized` **When triggered**: When an HTTP 401 response is received, or the business code in the response body (`codeKey`, string values included) is 401, **before** `movk:api:error`. Upload / download progress requests are covered as well. ```ts 'movk:api:unauthorized': ( context: FetchContext, result: { handled: boolean } ) => void | Promise ``` Setting `result.handled = true` **skips the default 401 handling** (clearing the session and redirecting to the login page), as well as `movk:api:error` and the error Toast (the failed request itself still rejects with `ApiError`). > [!WARNING] > > If multiple handlers listen to this hook, any handler setting > > result.handled = true > > will prevent the default behavior. #### Token Refresh Pattern ```ts [app/plugins/token-refresh.ts] export default defineNuxtPlugin((nuxtApp) => { let refreshing: Promise | null = null nuxtApp.hook('movk:api:unauthorized', async (_context, result) => { // Run cookie-based session refresh on the client only if (import.meta.server) return try { // Share one in-flight promise across concurrent 401s so all of them await & set handled refreshing ??= $fetch('/api/auth/refresh', { method: 'POST' }) .then(() => useUserSession().fetch()) .finally(() => { refreshing = null }) await refreshing result.handled = true // Re-run active useApiFetch / useAsyncData queries on the current page await refreshNuxtData() } catch { // Leave handled = false so Movk clears the session and redirects to login } }) }) ``` ## Registration ### In a Nuxt Plugin (Recommended) Suitable for global logic that is automatically registered at app startup: ```ts [plugins/api-hooks.ts] export default defineNuxtPlugin((nuxtApp) => { nuxtApp.hook('movk:api:request', (context) => { // Global request handling }) nuxtApp.hook('movk:api:error', (context, error) => { // Global error handling }) }) ``` ### In a Component Suitable for page-scoped logic: ```vue ``` > [!NOTE] > > When registering hooks inside a component, always call the returned unregister function in > > onUnmounted > > to avoid memory leaks. ## Execution Order ```text Request initiated │ ├── Auth token injection ├── Debug logging ├── movk:api:request <-- user extension point │ ├── Network request sent ─────────────> │ ├── HTTP 2xx response │ ├── Business success (code in successCodes, or businessCheck disabled) │ │ ├── Data unwrap (extract dataKey, skipped when unwrap is disabled) │ │ ├── movk:api:response <-- user extension point │ │ └── Success Toast │ │ │ └── Business failure → throw ApiError(kind: business), go to exit │ ├── HTTP 4xx/5xx → ofetch retries per retry option, still failing goes to exit ├── Network failure / timeout → go to exit │ └── Exit (runs once per request, skipped on abort) ├── Normalize to ApiError ├── [HTTP or business code 401] movk:api:unauthorized <-- user extension point │ └── (if not handled) clear session + redirect to login ├── movk:api:error <-- user extension point (skipped for handled 401) ├── Error Toast <-- skipped for handled 401 └── throw ApiError ``` ## TypeScript Support Hook types are automatically registered via module declaration: ```ts [src/runtime/types/module.ts] declare module 'nuxt/app' { interface RuntimeNuxtHooks { 'movk:api:request': (context: FetchContext) => void | Promise 'movk:api:response': (context: FetchContext & { response: FetchResponse }) => void | Promise 'movk:api:error': (context: FetchContext, error: ApiError) => void | Promise 'movk:api:unauthorized': ( context: FetchContext, result: { handled: boolean } ) => void | Promise } } ``` No additional configuration is needed — `nuxtApp.hook('movk:api:...')` provides full type inference and auto-completion out of the box. # useApiFetch > An API request composable built on Nuxt useFetch, providing automatic authentication, business status code checking and Toast notifications. ## Usage Use the auto-imported `useApiFetch` composable for API requests. Built on top of Nuxt [`useFetch`](https://nuxt.com/docs/api/composables/use-fetch), it provides automatic authentication, data unwrapping, business status code checking and unified error handling. ```vue ``` - `useApiFetch` inherits all features of Nuxt [`useFetch`](https://nuxt.com/docs/api/composables/use-fetch) while providing additional API integration. - Automatically retrieves the token from the session and adds it to request headers (via the `$api` instance). - Automatically checks business status codes and throws errors. - Built-in Toast notifications with customizable configuration. ## Data Request Patterns Movk Nuxt provides three data request composables with identical signatures — choose based on execution timing: | Composable | Execution | Blocks Navigation | Use Case | | --- | --- | --- | --- | | [`useApiFetch`](https://nuxt.mhaibaraai.me/en/docs/api/use-api-fetch) | SSR + CSR | Yes | Above-the-fold core data | | [`useLazyApiFetch`](https://nuxt.mhaibaraai.me/en/docs/api/use-api-fetch#uselazyapifetch) | SSR + CSR | No | Secondary / non-above-the-fold data | | [`useClientApiFetch`](https://nuxt.mhaibaraai.me/en/docs/api/use-api-fetch#useclientapifetch) | CSR only | No | Non-SEO-sensitive data | `useApiFetch` fires the request during SSR, delivering data on first render: ```vue [ApiQuickstartSsrExample.vue] ``` ## Data Unwrapping and Transformation `useApiFetch` already receives the business data unwrapped by [`$api`](https://nuxt.mhaibaraai.me/en/docs/api/api-plugin#data-unwrapping-and-business-validation); the generic `T` directly declares that data type. `transform` receives the unwrapped data for a secondary transformation: ```ts // Generic T directly declares the business data type (the type of the data field) const { data } = await useApiFetch('/user') // data.value = { id: 1, name: 'test' } // Combine with transform for a secondary transformation const { data } = await useApiFetch<{ content: User[] }, SelectItem[]>('/users', { transform: ({ content }) => content.map(u => ({ label: u.name, value: u.id })) }) ``` > [!TIP] > See: /en/docs/api/api-plugin#data-unwrapping-and-business-validation > > See the > > $api > > page for interactive examples of the unwrapping mechanism and > > unwrap > > / > > businessCheck ## Business Status Code Checking The `$api` interceptor automatically checks the business status code and throws an `ApiError` (see [Error Classification](#error-classification) below) when the code is not in `successCodes`. Pass `businessCheck: false` to disable validation, while the `dataKey` field is still unwrapped: ```ts const { data } = await useApiFetch('/external', { businessCheck: false }) ``` When a whole endpoint returns no envelope, declare it on the endpoint `response` instead of passing options per request: ```ts const { data } = await useApiFetch('/point-numbers', { endpoint: 'sensor' }) ``` > [!TIP] > See: /en/docs/api/api-plugin#endpoint-level-declaration > > See the > > $api > > page for endpoint-level declaration and precedence ## Error Classification Every failure becomes an [`ApiError`](https://nuxt.mhaibaraai.me/en/docs/api/api-plugin#apierror) (`NuxtError`), kept intact by `useAsyncData`; distinguish scenarios with `error.value.data.kind`. Select an error type in the dropdown to observe the shape of `error.value`: - `business`: HTTP 200 but `code` not in `successCodes`; `data.code` keeps the original business code. - `http-400` / `http-500`: `kind` is `http` and `statusCode` the corresponding code; a GET 5xx is retried once by ofetch's default and reported only once. - `http-422`: `data.response` carries additional server information. - `network`: Connection forcibly cut; the request received no response. - `timeout`: Exceeded the milliseconds set by `timeout`. ```vue [ApiErrorsExample.vue] ``` ## Toast Notifications The `toast` option supports per-request configuration: `false` to disable all, `{ success: false }` to keep only errors, `successMessage` / `errorMessage` for quick text, or a full set of [`Toast`](https://ui.nuxt.com/components/toast) props (`color`, `icon`, `duration`, etc.): ```ts // Disable Toast / keep error only / quick text await useApiFetch('/users', { toast: false }) await useApiFetch('/users', { toast: { success: false } }) await useApiFetch('/users', { toast: { successMessage: 'Created!', errorMessage: 'Failed, please retry' } }) // Full Toast props await useApiFetch('/users', { toast: { success: { title: 'Created', color: 'success', icon: 'i-lucide-circle-check' }, error: { title: 'Failed', color: 'error', duration: 5000 } } }) // Re-enable a globally disabled toast for one request await useApiFetch('/users', { toast: { success: { show: true } } }) // Custom text counts as the same intent: it shows even when the toast is // globally disabled or the method misses the whitelist await useApiFetch('/users', { toast: { successMessage: 'Created!' } }) ``` > [!NOTE] > > Precedence: request-level > > show > > > request-level > > successMessage > > / > > errorMessage > > > global > > success.show > > / > > error.show > > / > > methods > > > global > > enabled > > . With > > toast.success.show: false > > set globally, both > > { success: { show: true } } > > and > > { successMessage: '...' } > > still show the toast; pass > > { success: false } > > or > > { success: { show: false } } > > to stay silent. > [!TIP] > See: /en/docs/getting-started/configuration#toast-options > > To notify only on POST / PUT / PATCH / DELETE, set > > toast.success.methods > > in the global or endpoint config — the field is not accepted per request > [!TIP] > See: /en/docs/api/api-plugin#toast-notifications > > See interactive examples for five Toast modes on the > > $api > > page ## API ### useApiFetch() `useApiFetch(url: string | (() => string), options?: UseApiFetchOptions): UseApiFetchReturn`{lang="ts-type"} Creates an API request. #### Parameters **url** (`string | (() => string)`) *required*: Request URL or a function returning the URL. Supports reactive URLs. **options** (`UseApiFetchOptions`): Request configuration options. Supports all Nuxt useFetch options plus additional API integration options.API Integration OptionsUse the specified endpoint configuration. Defaults to the default endpoint of $api.Toast notification configuration. Set to false to disable Toast.Success notification configuration. Can be a full Toast props object or false to disable success notifications.Error notification configuration. Can be a full Toast props object or false to disable error notifications.Quick text for success notifications. Equivalent to success: { title: '...' }.Quick text for error notifications. Equivalent to error: { title: '...' }.Whether to validate the business status code. Inherits the endpoint / global response.businessCheck when omitted; when false, no business ApiError is thrown but the dataKey field is still unwrapped.Whether to unwrap by dataKey. Inherits the endpoint / global response.unwrap when omitted; when false, returns the raw response body. Orthogonal to businessCheck.Request Options (inherited from useFetch)HTTP method. Defaults to 'GET'.URL query parameters, automatically serialized into the URL.Alias for query.Request body. Automatically serialized to JSON for POST/PUT/PATCH requests.Request headers.Base URL. Usually configured via the endpoint option; no need to set manually.Response HandlingFunction to transform response data. Receives the unwrapped business data and returns the final data.Select only the specified fields from the response data.Factory function to set a default value.Execution OptionsWhether to execute the request immediately. Set to false to call execute() manually. Defaults to true.Whether to use lazy mode. In lazy mode, client-side navigation is not blocked and data loads in the background. Defaults to false.Whether to execute the request on the server. Defaults to true.Reactive sources to watch; the request re-fires automatically on change. Can be a ref, reactive object or array.Whether to deep-watch the watch objects. Defaults to true.Caching and DeduplicationCustom cache key. Used for sharing data between requests or deduplication.Strategy for handling duplicate requests. Defaults to cancel.'cancel' — Cancel the pending request'defer' — Do not initiate a new requestFunction to retrieve data from cache. The return value is used as the initial data.Request HooksHook called before the request is sent. Merged with built-in hooks.onRequest({ request, options }) { console.log('Sending request:', request.url) } Hook called on request error. Merged with built-in hooks.onRequestError({ request, error }) { console.error('Request error:', error) } Hook called when a response is received. Built-in hooks run first, so response._data is already the unwrapped business data (unless unwrap is false); only fires on business success. Return values are ignored by ofetch — use transform for output transformations.onResponse({ response }) { console.log('Unwrapped data:', response._data) } Hook called on response error (4xx/5xx). Passed to ofetch as-is and fires on every failed attempt, including retries; use the movk:api:error hook for unified error handling.onResponseError({ response }) { console.error('Response error:', response.status) } #### Type Parameters **T** (`type`): Business data type (already automatically unwrapped by $api). This is the data type of the data field in the API response. **DataT** (`type`): The final type after transform conversion. Defaults to T. #### Returns Returns the response object of [`useFetch`](https://nuxt.com/docs/api/composables/use-fetch#return-values), including: **data** (`Ref`): Response data (unwrapped and transformed). Initially null; updated to the actual data after a successful request. **error** (`Ref`): Error object. Every failure is an ApiError; distinguish business, HTTP, network and timeout errors via data.kind. **status** (`Ref<'idle' | 'pending' | 'success' | 'error'>`): Request status.'idle' — Not yet started (only when immediate: false)'pending' — Request in progress'success' — Request succeeded'error' — Request failed **pending** (`Ref`): Whether a request is in progress. Equivalent to status.value === 'pending'. **refresh** (`(opts?: { dedupe?: boolean }) => Promise`): Refresh data by re-executing the request. Alias: execute.// Refresh data await refresh() // Skip deduplication check and force refresh await refresh({ dedupe: false }) **execute** (`(opts?: { dedupe?: boolean }) => Promise`): Alias for refresh. Manually execute the request (commonly used with immediate: false). **clear** (`() => void`): Clear state: sets data to null, error to null and status to 'idle'. ## useLazyApiFetch ### Usage Use the auto-imported `useLazyApiFetch` composable for API requests. Equivalent to `useApiFetch(url, { ...options, lazy: true })`. In lazy mode the request does not block client-side navigation; the page renders immediately and data loads in the background. ```vue ``` - `useLazyApiFetch` does not block client-side navigation, making it suitable for non-critical data (user lists, comments, etc.). - During client-side navigation `data` is initially `null` and `status` is `'pending'`; you must handle the loading state. - Inherits all features of `useApiFetch` (auth, Toast, business status code checking, etc.). > [!NOTE] > > For data that is required on first render, use > > useApiFetch > > (non-lazy mode) to block navigation and ensure data is ready. > [!TIP] > See: /en/docs/api/use-api-fetch > > See the > > useApiFetch > > documentation for full API options and feature descriptions ### Example The page renders first, then enters the pending state. `data` is `null` until the response arrives; pair with `pending` / `status` to handle the loading state: ```vue [ApiQuickstartLazyExample.vue] ``` ### API #### useLazyApiFetch() `useLazyApiFetch(url: string | (() => string), options?: UseApiFetchOptions): UseApiFetchReturn`{lang="ts-type"} Creates a lazy API request. ##### Parameters **url** (`string | (() => string)`) *required*: Request URL or a function returning the URL. Supports reactive URLs. **options** (`UseApiFetchOptions`): Request configuration options. Supports all options of useApiFetch.[!NOTE]The lazy option is forced to true; no need to specify it manually. ##### Type Parameters **T** (`type`): Business data type (already automatically unwrapped by $api). **DataT** (`type`): The final type after transform conversion. Defaults to T. ##### Returns Same return value as [`useApiFetch`](https://nuxt.mhaibaraai.me/en/docs/api/use-api-fetch#returns). ### Changelog See commit history for [src/runtime/composables/useApiFetch.ts](https://github.com/mhaibaraai/movk-nuxt/commits/main/src/runtime/composables/useApiFetch.ts). ## useClientApiFetch ### Usage Use the auto-imported `useClientApiFetch` composable for client-only API requests. Equivalent to `useApiFetch(url, { ...options, server: false, lazy: true })`. ```vue ``` - `useClientApiFetch` inherits all features of [`useApiFetch`](https://nuxt.mhaibaraai.me/en/docs/api/use-api-fetch) (auth, Toast, business status code checking, etc.). - Presets `server: false` + `lazy: true` — requests do not block navigation and execute only on the client. - By default, fires automatically after hydration. Pass `immediate: false` for manual control. > [!WARNING] > > Due to > > server: false > > , there is no data during SSR. On initial render > > data > > is > > null > > ; use > > pending > > or > > status > > to manage the loading state. ### Example Skips SSR; the request fires only after browser hydration. `data` is `null` on initial render during SSR: ```vue [ApiQuickstartClientExample.vue] ``` ### API #### useClientApiFetch() `useClientApiFetch(url: string | (() => string), options?: UseApiFetchOptions): UseApiFetchReturn`{lang="ts-type"} Creates a client-only API request. ##### Parameters **url** (`string | (() => string)`) *required*: Request URL or a function returning the URL. **options** (`UseApiFetchOptions`): Request configuration options. See useApiFetch for the full option reference.The following options are forced and cannot be overridden via options:server: false — Disables server-side executionlazy: true — Enables lazy mode (does not block navigation) ##### Type Parameters Same as [`useApiFetch`](https://nuxt.mhaibaraai.me/en/docs/api/use-api-fetch#type-parameters). ##### Returns Same return value as [`useApiFetch`](https://nuxt.mhaibaraai.me/en/docs/api/use-api-fetch#returns). ### Changelog See commit history for [src/runtime/composables/useApiFetch.ts](https://github.com/mhaibaraai/movk-nuxt/commits/main/src/runtime/composables/useApiFetch.ts). # Upload and Download > File upload and download with progress tracking. ## useUploadWithProgress ### Usage `useUploadWithProgress` plugs an XHR adapter in as the underlying fetch of the same `$api` pipeline (the fetch spec still cannot report upload progress in mainstream browsers), so endpoint headers, auth, business validation, Toast, error normalization and `movk:api:*` hooks match `useApiFetch` exactly. The returned `data` is unwrapped per the endpoint policy and every failure is an `ApiError`. ```vue ``` > [!NOTE] > > Use this for scenarios that require displaying upload progress. For small files where progress is not needed, you can use > > $api > > directly. ### Basic Multi-File Upload `fieldName` determines the FormData field name (defaults to `'file'`); `upload()` returns `{ data, error, aborted }`: ```vue [ComposablesUseUploadProgressBasicExample.vue] ``` ### Single File, Multiple Files and Extra Fields Pass a `File` for single-file upload or a `File[]` for multiple files (appended under the same `fieldName`); `fields` injects extra form fields submitted alongside the file: ```ts await upload('/api/upload', file, { fieldName: 'file' }) await upload('/api/upload', [f1, f2, f3], { fieldName: 'files' }) await upload('/api/upload', file, { fieldName: 'avatar', fields: { userId: '123', visibility: 'private' } }) ``` ```vue [ComposablesUseUploadProgressSingleExample.vue] ``` ### Timeout `timeout` sets the upload timeout in milliseconds (0 or omitted means no timeout). On timeout the request is aborted with a `TimeoutError` and `error.data.kind` is `timeout`: ```vue [ComposablesUseUploadProgressTimeoutExample.vue] ``` ### Cross-Origin Credentials ```ts await upload('https://other.example/upload', file, { withCredentials: true }) ``` ### Abort Upload ```ts const { status, upload, abort } = useUploadWithProgress() upload('/api/upload', largeFile) function handleCancel() { if (status.value === 'pending') abort() } ``` After aborting: - `status` changes to `'aborted'`; `progress` resets to `0` - `error` remains `null` (not treated as failure) - `onSuccess` / `onError` are not called; no Toast is shown - `upload()` returns `{ data: null, error: null, aborted: true }` ### Authentication The token is automatically read from the session and injected into the `Authorization` header. You can override it with the same header name in `headers` (user value takes priority). ```ts await upload('/api/upload', file, { headers: { Authorization: 'Bearer override' } }) ``` ### API #### useUploadWithProgress() `useUploadWithProgress(): { progress, status, data, error, upload, abort }`{lang="ts-type"} ##### Returns **progress** (`Ref`): Upload progress, 0–100. Aligned with the download-side type, null is retained as a possible value but does not occur in practice for uploads. **status** (`Ref`): Transfer status: 'idle' | 'pending' | 'success' | 'error' | 'aborted'. **data** (`Ref`): Business data unwrapped by dataKey. **error** (`Ref`): Error object. Business errors are ApiError; HTTP/network errors are Error. null on abort. **upload()** (`(url: string, files: File | File[], options?: UploadWithProgressOptions) => Promise>`): Execute the upload.ParametersDefaults to 'file'.Merged with the endpoint headers; when auth is enabled the auth header is injected last and takes the highest priority, same as $api.Whether to validate the business status code; inherits the endpoint config when omitted. When false, still unwraps by dataKey.Whether to unwrap by dataKey; inherits the endpoint config when omitted.Timeout in milliseconds. 0 or omitted means no timeout.Receives the unwrapped business data.ReturnsPromise>: { data: T | null, error: ApiError | null, aborted: boolean }. **abort()** (`() => void`): Abort the current upload; status switches to 'aborted'. ### Changelog See commit history for [src/runtime/composables/upload and Download.ts](https://github.com/mhaibaraai/movk-nuxt/commits/main/src/runtime/composables/upload and Download.ts). ## useDownloadWithProgress ### Usage `useDownloadWithProgress` reads a streamed response through `$api.raw` and reports progress, so endpoint headers, auth, business validation, Toast, error normalization and `movk:api:*` hooks match `useApiFetch` exactly; the request body is serialized by ofetch and every failure is an `ApiError`. When the backend returns `application/json`, business validation is applied and error responses are **not** written to a file as binary. When binary data is returned, progress is calculated from `content-length`; when `content-length` is missing, `progress` is `null` and the UI can switch to indeterminate accordingly. ```vue ``` > [!NOTE] > > Use this for large file exports, bulk downloads and similar scenarios. For small files where progress is not needed, use > > $api > > directly. ### Basic Download When `content-length` is known, progress updates proportionally; `abort()` stops the stream read: ```vue [ComposablesUseDownloadProgressBasicExample.vue] ``` ### Filename Resolution Priority order: 1. `options.filename` 2. Response header `Content-Disposition` (supports RFC 5987 encoding) 3. Last segment of the URL pathname (query string is automatically stripped) 4. `'download'` ```ts await download('/api/export?token=abc') // Automatically uses "export" as the fallback filename; query string does not pollute the name ``` ### Indeterminate Progress When the response is missing `content-length` (e.g. chunked transfer encoding), `progress` is `null`. Using nullish-coalescing to map it to `UProgress`'s `:model-value` automatically activates the indeterminate state: ```vue [ComposablesUseDownloadProgressChunkedExample.vue] ``` ### Custom Filename `options.filename` overrides the response header and URL inference to force a specific download filename: ```vue [ComposablesUseDownloadProgressCustomExample.vue] ``` ### POST Export `method: 'POST'` + `body` puts filter criteria in the request body; `Content-Type` is automatically set to `application/json`: ```vue [ComposablesUseDownloadProgressPostExample.vue] ``` ### Abort Download ```ts const { status, download, abort } = useDownloadWithProgress() download('/api/export/large.zip') function handleCancel() { if (status.value === 'pending') abort() } ``` After aborting: - `status` changes to `'aborted'`; `progress` resets to `0` - `error` remains `null` (not treated as failure) - `onError` is not called; no Toast is shown - `download()` returns `{ data: null, error: null, aborted: true }` ### Authentication The token is automatically read from the session and injected into the `Authorization` header. Override it in `headers` if needed (user value takes priority). ```ts await download('/api/export/private.pdf', { headers: { 'X-Custom': 'value' } }) ``` ### API #### useDownloadWithProgress() `useDownloadWithProgress(): { progress, status, data, error, download, abort }`{lang="ts-type"} ##### Returns **progress** (`Ref`): Download progress, 0–100. null when content-length is missing; the UI should switch to indeterminate in that case. **status** (`Ref`): Transfer status: 'idle' | 'pending' | 'success' | 'error' | 'aborted'. **data** (`Ref`): In the binary path, a Blob. In the JSON path, the unwrapped business data. **error** (`Ref`): Error object. Business errors are ApiError; HTTP/network errors are Error. null on abort. **download()** (`(url: string, options?: DownloadWithProgressOptions) => Promise>`): Execute the download.ParametersDefaults to 'GET'.Serialized to JSON for non-GET requests.Merged with the endpoint headers; when auth is enabled the auth header is injected last and takes the highest priority, same as $api.Whether to validate the business status code; inherits the endpoint config when omitted. When false, still unwraps by dataKey.Whether to unwrap by dataKey; inherits the endpoint config when omitted.ReturnsPromise>: { data: T | null, error: ApiError | null, aborted: boolean }. **abort()** (`() => void`): Abort the current download; status switches to 'aborted'. ### Changelog See commit history for [src/runtime/composables/upload and Download.ts](https://github.com/mhaibaraai/movk-nuxt/commits/main/src/runtime/composables/upload and Download.ts). # Streaming > SSE streaming requests and the AI SDK chat transport. ## useApiStream ### Usage `useApiStream` is the reactive shell around [`$api.stream()`](#apistream). It returns a lazy async generator: the request only starts once you begin iterating. Line buffering, multi-line `data:` concatenation, comment lines and `\r\n` handling are delegated to `eventsource-parser`; events that fail to parse are skipped silently — a heartbeat or handshake line should never break the whole stream. ```vue ``` Starting a new stream aborts the previous one, and so does the component scope being disposed. ### How Accept and responseType are handled > [!WARNING] > > Both defaults were settled the hard way. Check your gateway's behaviour before changing them. **Accept defaults to the wildcard — neither `application/json` nor `text/event-stream`.** ofetch automatically adds `Accept: application/json` whenever the body is JSON-serializable, which is simply the wrong claim for a request you intend to read as a stream: a backend negotiating on `Accept` may switch to its JSON renderer because of it. Sending `Accept: text/event-stream` instead gets the whole request rejected by those same backends (DRF, for instance) — verified against one that answers "cannot satisfy the Accept HTTP header" before any business logic runs. The wildcard avoids both. Gateways that need a specific value can pass one, and an explicit header always wins: ```ts stream('/chat', { headers: { Accept: 'text/event-stream' } }) ``` **`responseType: 'stream'` by default**: an event stream is read as a stream even when a gateway mislabels it as something other than `text/event-stream`. An `application/json` response (including HTTP 200 error envelopes like `{ code: 500 }`) is first restored to an object by the interceptor and then goes through business-code validation to surface the backend message, instead of turning into a stream that never yields anything. A readable error is thrown when the response body is not a stream, so nothing spins silently. ### Errors and aborts - Deliberate aborts (`abort()`, starting a new stream, scope disposal) are not errors: `status` becomes `'aborted'`, `error` stays `null` and iteration ends silently - Any other error is written to `error`, sets `status` to `'error'`, calls `onError` and is then **re-thrown**, so a `try/catch` around `for await` can handle it - Business errors (a `code` outside `successCodes`) are thrown by the interceptor before the stream starts, with the toast and the `movk:api:error` hook firing as usual ```ts try { for await (const chunk of stream('/chat', { onError: e => console.error(e) })) { // ... } } catch (error) { // business error, HTTP error or broken stream } ``` ### $api.stream() Outside components, or when reactive state is not needed, call `$api.stream()` directly: ```ts const { $api } = useNuxtApp() for await (const chunk of await $api.stream('/chat', { method: 'POST', body })) { console.log(chunk.content) } ``` When the response is a stream the response interceptor short-circuits entirely — no unwrapping, no business-code check, no success toast — and `_data` is left untouched, so callers no longer need `unwrap` / `businessCheck`. To plug into the AI SDK and `@nuxt/ui` Chat components, use [`createChatTransport`](https://nuxt.mhaibaraai.me/en/docs/api/stream) instead. ### API #### useApiStream() ##### Type Parameters **T** (`unknown`): Type of a single chunk. ##### Returns **status** (`Ref`): 'idle' | 'streaming' | 'success' | 'error' | 'aborted'. Stays 'idle' until iteration starts. **error** (`Ref`): Error information; deliberate aborts are not written here. **stream()** (`(url: string, options?: UseApiStreamOptions) => AsyncGenerator`): Starts the streaming request and yields chunks one by one.ParametersEndpoint name to use; defaults to defaultEndpoint.How to decode a single SSE event's data; return undefined to drop it. Defaults to a fault-tolerant JSON.parse.Failure callback; not triggered on deliberate aborts.Every other option is forwarded to ofetch: method, body, headers, query, responseType and so on. **abort()** (`() => void`): Aborts the current stream and sets status to 'aborted'. ### Changelog See commit history for [src/runtime/composables/streaming.ts](https://github.com/mhaibaraai/movk-nuxt/commits/main/src/runtime/composables/streaming.ts). ## createChatTransport ### Usage `@nuxt/ui`'s `UChat*` components render AI SDK `UIMessage`s; all protocol parsing lives in the `ai` package and only understands the AI SDK's own UI Message Stream format. Internal gateways (MaxKB, Dify, FastGPT, in-house ones) each ship a different chunk shape, and `createChatTransport` fills exactly that gap: **your domain code writes one stateless `select`, everything else is inherited from the AI SDK's `HttpChatTransport`.** > [!NOTE] > > Install > > ai > > (an optional peer of > > @movk/nuxt > > ) and > > @ai-sdk/vue > > , then import from the > > @movk/nuxt/ai > > subpath — the main entry never pulls in the AI SDK. ```vue ``` `createChatTransport` reads `$api` internally, so call it inside a setup scope. ### The select mapping `select` is a pure function: given one backend chunk, it states which UI parts that chunk produces; return `undefined` to produce nothing. The lifecycle is handled by the transport — `start` is emitted once, text blocks are opened and closed per `id`, and every unclosed block plus `finish` is flushed when the stream ends, so a missing end signal or a broken connection never leaves the message stuck in streaming. **id** (`string`): Text block id; deltas sharing an id are merged into one block. Omitted deltas go to the default block 'text-1'. **delta** (`string`): Incremental text for this chunk; empty means no text-delta is emitted. **end** (`boolean`): Closes that text block. **data** (`{ type: string, value: unknown, transient?: boolean }`): An extra custom data part, emitted as data-${type}. With transient: true it only reaches useChat's onData callback and is never written to message history. **finished** (`boolean`): Ends the whole stream; later chunks are ignored. Workflow-style gateways often carry node information alongside the answer. Route it through a `data` part to drive progress without polluting the message history: ```ts const transport = createChatTransport({ api: '/chat/completions', select: raw => ({ id: raw.runtime_node_id, delta: raw.content, end: raw.node_is_end, finished: raw.is_end, data: { type: 'node', value: { nodeId: raw.node_id, nodeIsEnd: raw.node_is_end }, transient: true } }) }) const { messages } = useChat({ transport, onData: (part) => { if (part.type === 'data-node') advanceStage(part.data) } }) ``` ### Request orchestration `api`, `headers`, `body`, `credentials`, `prepareSendMessagesRequest` and `prepareReconnectToStreamRequest` are the AI SDK `HttpChatTransport` options and behave identically. A private handshake (open a session first, then build the stream URL) belongs in `prepareSendMessagesRequest`, which may be async and may override `api`: ```ts const transport = createChatTransport({ prepareSendMessagesRequest: async ({ messages }) => { const chatId = await $api('/chat/open') return { api: `/chat_message/${chatId}`, body: { message: getTextFromMessage(messages.at(-1)!) } } }, select }) ``` ### Why the default fetch goes through $api The injected default `fetch` is backed by `$api`, so endpoint baseURL, auth headers, business-code validation, error toasts and the `movk:api:*` hooks all apply. That is not only convenience: **some gateways return errors as HTTP 200 with a `{ code: 500 }` envelope**, which any `response.ok` check happily lets through before reading JSON as a stream and spinning forever. Through `$api` such a response throws at the business-code check and lands in `useChat`'s `onError`. It also takes care of `Accept`: ofetch adds `Accept: application/json` whenever the body is JSON, which is the wrong claim for a stream, so the default is switched to the wildcard. An explicit `headers` entry always wins. See [`useApiStream`](https://nuxt.mhaibaraai.me/en/docs/api/stream#how-accept-and-responsetype-are-handled) for the details. Passing your own `fetch` overrides the default, `Accept` included. ### API #### createChatTransport() ##### Type Parameters **Raw** (`unknown`): Type of a single backend chunk. **UI_MESSAGE** (`UIMessage`): Message type; defaults to the AI SDK UIMessage. ##### Parameters **options** (`MovkChatTransportOptions`) *required*: Pure mapping from a backend chunk to UI parts.Endpoint name to use; defaults to defaultEndpoint.How to decode a single SSE event's data; return undefined to drop it. Defaults to a fault-tolerant JSON.parse.api, headers, body, credentials, fetch, prepareSendMessagesRequest, prepareReconnectToStreamRequest — same semantics as the AI SDK. ##### Returns `ChatTransport`, ready to hand to `useChat({ transport })`. ### Changelog See commit history for [src/runtime/domains/ai/streaming.ts](https://github.com/mhaibaraai/movk-nuxt/commits/main/src/runtime/domains/ai/streaming.ts). # API Architecture > Clarify @movk/nuxt's responsibility boundary, organize direct backend calls, same-origin proxies, and minimal BFFs with lean layers, and wire up both authentication patterns. When setting up a Nuxt project with `@movk/nuxt`, over-complication almost always comes from two habits: **wrapping `$api` / `useApiFetch` in another custom interceptor layer**, and **writing dozens of pass-through BFF files or wrapper functions just to rename fields or expose REST routes**. This guide establishes a practical boundary, selection order, strict layering rules, and minimal examples so your API layer stays flat and maintainable. ## Responsibility Boundary Separate what `@movk/nuxt` already handles from what your application decides: | Owner | Responsibilities | Reference | | --- | --- | --- | | **Built into `@movk/nuxt`** | Multi-endpoint `$api` creation & caching, isolating server-only `headers` from client `publicHeaders` | [Endpoints](https://nuxt.mhaibaraai.me/en/docs/getting-started/configuration#endpoints) · [$api](https://nuxt.mhaibaraai.me/en/docs/api/api-plugin) | | **Built into `@movk/nuxt`** | Automatic token injection from session, 401 session cleanup & login redirect, `movk:api:unauthorized` hook | [Auth Integration](https://nuxt.mhaibaraai.me/en/docs/api/api-plugin#auth-integration) · [Hooks](https://nuxt.mhaibaraai.me/en/docs/api/hooks#movkapiunauthorized) | | **Built into `@movk/nuxt`** | Business status checks (`businessCheck`), unwrapping (`unwrap`), normalized `ApiError`, method-filtered toasts | [Overview](https://nuxt.mhaibaraai.me/en/docs/api) · [$api](https://nuxt.mhaibaraai.me/en/docs/api/api-plugin) | | **Built into `@movk/nuxt`** | SSR/CSR caching & dedupe keys (`useApiFetch` family), upload/download progress, SSE streaming | [useApiFetch](https://nuxt.mhaibaraai.me/en/docs/api/use-api-fetch) · [Upload & Download](https://nuxt.mhaibaraai.me/en/docs/api/upload-download) · [Streaming](https://nuxt.mhaibaraai.me/en/docs/api/stream) | | **Your Application** | Choosing direct / same-origin proxy / minimal BFF per endpoint, domain contracts, and thin server boundaries | This guide | > [!NOTE] > > The API domain relies on the Nuxt runtime and server-private > > runtimeConfig > > isolation — > > it is only available in Nuxt mode > > . Plain Vue + Vite mode includes UI components, AutoForm, DataTable, and general-purpose composables. ## Selection Decision Tree Evaluate every backend integration in the order **Direct → Same-Origin Proxy → Minimal BFF**. One project can mix all three via multiple endpoints: ```mermaid flowchart TD A["Add a new backend endpoint group"] --> B{"Supports CORS and browser can send credentials directly?"} B -- "Yes" --> C["Direct Backend: configure endpoint baseURL only"] B -- "No" --> D{"Browser session already authorized; only need CORS, same-origin cookies, or runtime host?"} D -- "Yes" --> E["Same-Origin Proxy: /proxy/:target/* -> upstream"] D -- "No (privileged session switch / tenant lock / secrets / multi-step login / fan-out / binary cache)" --> F["Minimal BFF: server/api/ -> single gateway entry"] ``` | Pattern | Request Path | When to Choose It | | --- | --- | --- | | **Direct Backend** | App → Backend | Public API or CORS-enabled backend where the browser carries credentials directly — zero server code | | **Same-Origin Proxy** | App → `/proxy/**` → Backend | Browser's own session already authorizes the upstream path (e.g. `/proxy/gateway/:menuId/:buttonId`); you only hide internal hosts, avoid CORS, share cookies, or switch upstream URLs at runtime | | **Minimal BFF** | App → `server/api/` → Upstream | Requires server-only secrets, privileged session switching with server-enforced tenant params, multi-step login cookie setup, multi-upstream aggregation, sharded concurrency limits, or binary packing & caching | > [!TIP] > > **Do not build a BFF just to rename fields or proxy direct gateway paths**: > > - When an upstream returns `snake_case` or bare arrays, disable `businessCheck` and `unwrap` on that endpoint, put a Zod `.transform()` in `shared/contracts/`, and pass it to `useApiFetch`'s `transform` option once on the client. > - If the browser's own session already has permission to call a gateway path and the backend isolates tenants by session, call the same-origin proxy directly from `app/composables/api/` without a BFF. ## Layering Rules (Hard Constraints) Keep every request path easy to trace by following six constraints: 1. **Parse contracts once**: keep Zod schemas and field mappings in `shared/contracts/`. Direct/proxy endpoints parse once in the composable or `transform`; BFFs output the final view model without re-parsing on both sides. 2. **Call directly per domain on the client**: organize `app/composables/api/` by domain and call `$api`, `useApiFetch`, or `useClientApiFetch` directly — never add a custom `request.ts` wrapper. 3. **One upstream factory and one entry on the server**: keep a single upstream client factory (timeout, logging, `502/504` mapping) and a single call helper per upstream family (context switching + envelope unwrapping) in `server/utils/`. 4. **Keep routes as thin gatekeepers**: `server/api/` handlers only validate params/body, call one service/helper function, and return the unified response envelope — no loops, retries, or aggregations inside route files. 5. **At most two server layers per upstream**: `route → single upstream entry → upstream`. Never stack specialized pass-through helpers on top of generic helpers. 6. **Eliminate single-caller wrappers and shell routes**: inline any helper with only one caller; consolidate repetitive BFF CRUD/query endpoints into **dual read/write operation tables** (`query/[op].get.ts` + `action/[op].post.ts`) instead of maintaining dozens of `[id].get/put/delete.ts` files. ## Three Integration Patterns Example ::code-tree{:expand-all="true" default-value="nuxt.config.ts"} ```ts [nuxt.config.ts] const baseURL = process.env.NUXT_APP_BASE_URL || '/' export default defineNuxtConfig({ modules: ['@movk/nuxt'], app: { baseURL }, // Injected at container runtime via NUXT_GATEWAY_URL / NUXT_SENSOR_URL / NUXT_ORDERS_TOKEN runtimeConfig: { gatewayUrl: '', sensorUrl: '', ordersToken: '' }, movk: { api: { // Show automatic success toasts only for mutating methods; keep GET queries silent toast: { success: { methods: ['POST', 'PUT', 'PATCH', 'DELETE'] } }, endpoints: { // 1. Minimal BFF: enables { code, message, data } validation and unwrapping by default default: { baseURL: `${baseURL}api` }, // 2. Same-origin proxy: mostly raw responses; opt in per request when needed gateway: { baseURL: `${baseURL}proxy/gateway`, response: { businessCheck: false, unwrap: false, messageKey: 'msg' } }, // 3. Unauthenticated service returning bare arrays: disable auth to prevent token leaks & false logouts sensor: { baseURL: `${baseURL}proxy/sensor`, response: { businessCheck: false, unwrap: false }, auth: { enabled: false, unauthorized: { clearSession: false, redirect: false } } } } } } }) ``` ```ts [shared/contracts/sensor.ts] import { z } from 'zod' // Convert upstream snake_case once in the shared contract layer — no pass-through BFF needed const upstreamReadingSchema = z.object({ point_number: z.string(), sensor_value: z.number().nullable() }).transform(({ point_number, sensor_value }) => ({ pointNumber: point_number, value: sensor_value })) export type SensorReading = z.infer export const parseReadings = (raw: unknown): SensorReading[] => z.array(upstreamReadingSchema).parse(raw) ``` ```ts [app/composables/api/useSensor.ts] import { parseReadings, type SensorReading } from '#shared/contracts/sensor' export function useSensorLatest(point: Ref, active: Ref) { return useClientApiFetch('/readings/latest', { endpoint: 'sensor', query: { point }, enabled: computed(() => active.value && Boolean(point.value)), transform: parseReadings, toast: false }) } export async function fetchCaptcha() { const { $api } = useNuxtApp() // Opt into envelope checking and unwrapping for a single endpoint route return await $api.use('gateway')<{ captchaId: string, img: string }>('/v1/captcha/get', { businessCheck: true, unwrap: true, toast: { success: false } }) } ``` ```ts [app/composables/api/useAdmin.ts] // For BFF-protected operations, align the client with two 1-line helpers against the read/write tables export function useAdminApi() { const { $api } = useNuxtApp() const query = (op: 'users' | 'roles' | 'userDetail', params?: Record) => $api(`/admin/query/${op}`, { ...(params ? { query: params } : {}) }) const act = (op: 'createUser' | 'removeUser', body: Record) => $api(`/admin/action/${op}`, { method: 'POST', body }) return { listUsers: (params: { page: number }) => query('users', params), getUserDetail: (id: string) => query('userDetail', { id }), createUser: (body: { name: string }) => act('createUser', body), removeUser: (id: string) => act('removeUser', { id }) } } ``` ```ts [server/routes/proxy/[target]/[...path].ts] export default defineEventHandler((event) => { const target = getRouterParam(event, 'target') const config = useRuntimeConfig(event) // Restrict proxy targets with an explicit allowlist to prevent open proxy (SSRF) const upstreams: Record = { gateway: config.gatewayUrl, sensor: config.sensorUrl } const upstreamBase = target ? upstreams[target] : undefined if (!upstreamBase) { throw createError({ statusCode: 404, message: 'Unknown proxy target' }) } const path = getRouterParam(event, 'path') || '' if (path.split('/').includes('..')) { throw createError({ statusCode: 400, message: 'Invalid request path' }) } const { search } = getRequestURL(event) const base = new URL(upstreamBase.replace(/\/$/, '')) const targetUrl = `${base.origin}${base.pathname.replace(/\/$/, '')}/${path.replace(/^\//, '')}${search}` if (new URL(targetUrl).origin !== base.origin) { throw createError({ statusCode: 400, message: 'Invalid request path' }) } return proxyRequest(event, targetUrl) }) ``` ```ts [server/utils/upstream.ts] import type { z } from 'zod' export function parseUpstream(schema: z.ZodType, raw: unknown, name: string): T { const result = schema.safeParse(raw) if (!result.success) { console.error(`[upstream:${name}] schema mismatch`, result.error.issues.slice(0, 5)) throw createError({ statusCode: 502, message: `${name} returned an unexpected payload` }) } return result.data } export function createUpstream(name: string, baseURL: string, headers?: Record) { if (!baseURL) { throw createError({ statusCode: 500, message: `Missing ${name} baseURL` }) } return $fetch.create({ baseURL, headers, timeout: 10_000, retry: 0, onResponseError({ response }) { throw createError({ statusCode: response.status === 404 ? 404 : 502, message: `${name} error` }) }, onRequestError({ error }) { if (error.name === 'AbortError') throw error throw createError({ statusCode: error.name === 'TimeoutError' ? 504 : 502, message: `${name} unavailable` }) } }) } ``` ```ts [server/api/admin/query/[op].get.ts] import { z } from 'zod' // Consolidate reads & detail aggregations into GET ops (keeps GET silent without POST success toasts) const READS = { users: { schema: z.object({ page: z.coerce.number().default(1) }), run: (q: { page: number }) => queryAdmin('user.list', q) }, userDetail: { schema: z.object({ id: z.string().min(1) }), run: (q: { id: string }) => fetchUserDetail(q.id) } } as const const paramsSchema = z.object({ op: z.enum(['users', 'userDetail']) }) export default defineEventHandler(async (event) => { await requireUserSession(event) const { op } = await getValidatedRouterParams(event, paramsSchema.parse) const query = await getValidatedQuery(event, data => READS[op].schema.parse(data)) return { code: 200, message: 'ok', data: await READS[op].run(query) } }) ``` ```ts [server/api/admin/action/[op].post.ts] import { z } from 'zod' // Consolidate mutations into POST ops (automatically triggers toast.success.methods) instead of dozens of shell files const ACTIONS = { createUser: { schema: z.object({ name: z.string().min(1) }), run: (b: { name: string }) => saveUser(b), message: 'User created' }, removeUser: { schema: z.object({ id: z.string().min(1) }), run: (b: { id: string }) => deleteUser(b.id), message: 'User deleted' } } as const const paramsSchema = z.object({ op: z.enum(['createUser', 'removeUser']) }) export default defineEventHandler(async (event) => { await requireUserSession(event) const { op } = await getValidatedRouterParams(event, paramsSchema.parse) const body = await readValidatedBody(event, data => ACTIONS[op].schema.parse(data)) await ACTIONS[op].run(body) return { code: 200, message: ACTIONS[op].message, data: null } }) ``` :: > [!NOTE] > > Why > > createError({ statusCode, message }) > > instead of putting localized text in > > statusMessage > > ? > > HTTP status lines only allow ASCII characters — passing non-ASCII text in > > statusMessage > > causes Node / Undici to throw > > Invalid character in statusMessage > > as a 500 error. Put user-facing messages in > > message > > , which > > @movk/nuxt > > extracts automatically. ## Two Authentication Architectures Both patterns rely on `nuxt-auth-utils` for encrypted session cookies. **Always configure at least a 32-character `NUXT_APP_SECRET` in production.** ### Pattern A: Built-in Backend Auth (Backend Issues Token / SessionId) When an auth service or gateway issues tokens and expects them in a header (`Authorization: Bearer ` or a custom header like `sessionId`): 1. Enable `movk.api.auth.enabled: true` (reads `session.token` by default, injects the header, and handles 401 cleanup + `/login` redirect; for custom headers such as `sessionId`, set `headerName: 'sessionId', tokenType: 'Custom'`). 2. In your login handler, call `await setUserSession(event, { user, token })`. 3. On the login page after success, run `await useUserSession().fetch()` followed by `clearNuxtData()` before navigating so stale data from a previous account never flashes. 4. For silent token refresh, hook `movk:api:unauthorized`, set `result.handled = true` on success, and call `refreshNuxtData()`. > [!TIP] > > If security rules forbid exposing the raw token to browser JS, store it in > > setUserSession(event, { user, secure: { token } }) > > , set > > movk.api.auth.enabled: false > > , and inject > > secure.token > > inside > > proxy/[target]/[...path].ts > > using > > getUserSession(event) > > . ### Pattern B: No Built-in Backend Auth (Nuxt Manages Sessions, or Upstream Uses a Service Key) When upstreams only accept a static server API key or Nuxt handles user login directly: 1. Register `nuxt-auth-utils` explicitly in `modules` and keep `movk.api.auth.enabled: false` (`auth.unauthorized` still cleans up sessions and redirects on 401). 2. Call `const { user } = await requireUserSession(event)` in protected BFF routes before calling upstreams with private keys from `useRuntimeConfig(event)`. 3. Forward cookies to same-origin `/api` requests during SSR in `app/plugins/ssr-cookie.server.ts` (never forward cookies to external domains): ```ts [app/plugins/ssr-cookie.server.ts] export default defineNuxtPlugin((nuxtApp) => { const { cookie } = useRequestHeaders(['cookie']) if (!cookie) return nuxtApp.hook('movk:api:request', ({ request, options }) => { const base = options.baseURL || '' const url = typeof request === 'string' ? request : '' const isSameOrigin = (base.startsWith('/') && !base.startsWith('//')) || (!base && url.startsWith('/') && !url.startsWith('//')) if (!isSameOrigin) return const headers = new Headers(options.headers as HeadersInit | undefined) if (!headers.has('cookie')) { headers.set('cookie', cookie) options.headers = headers } }) }) ``` ## Anti-Pattern Checklist Any of the following signs means your API layer is becoming over-engineered and should be simplified immediately: | Anti-Pattern | Problem | Recommended Fix | | --- | --- | --- | | Writing a BFF just to rename fields | Adds extra network hops and dozens of pass-through routes | Disable `unwrap` on the endpoint and transform once in `shared/contracts/` via Zod | | Parsing twice on server and client | Server maps DTOs and client runs `safeParse` again | Pick one parsing boundary: parse in client composables for direct/proxy, or return view models directly from BFF | | One shell route per CRUD endpoint | Dozens of `[id].get/put/delete.ts` files repeating validate + forward | Consolidate into read/write operation tables (`query/[op].get.ts` + `action/[op].post.ts`) | | Multiple client factories per upstream | Timeout, logging, and error mapping diverge across files | Keep a single `createUpstream` and one entry helper in `server/utils/gateway.ts` | | Mixing incompatible envelopes | BFF mixes raw upstream envelopes with custom `{ code, data }` | Always return Movk's default envelope from custom BFFs; keep raw payloads on proxy/direct endpoints | | Single-caller intermediate wrappers | `route → helperA → helperB → service → client` indirection | Inline single-caller helpers; keep at most two server layers per upstream | | Non-ASCII text in `statusMessage` | Node/Undici rejects non-ASCII HTTP status lines with 500 | Always pass localized error text in `createError({ statusCode, message })` | ## New Endpoint Checklist Verify these seven items before adding a new backend integration: 1. **Choose the simplest topology**: prefer direct over proxy, and proxy over BFF; only use `server/api/` for secrets, privileged session switching/tenant locking, multi-step login, aggregations, sharded limits, or binary caching. 2. **Match endpoint config to payload shape**: disable `response.businessCheck`, `response.unwrap`, and `auth.enabled` for unauthenticated raw-payload endpoints. 3. **Keep a single parsing point**: store Zod schemas in `shared/contracts/` and validate/map once. 4. **Control toasts and concurrency**: keep `GET` quiet via `toast.success.methods`, and use `useAsyncData` + `Promise.all` instead of sequential `await useApiFetch` waterfalls. 5. **Handle `enabled` gating transitions**: `useAsyncData` / `useClientApiFetch` `enabled` only gates and aborts requests — it does not auto-trigger when switching `false → true`, so watch `enabled` and call `execute()` when `status === 'idle'`. 6. **Guard error boundaries**: map upstream schema mismatches and connection failures to `502` / `504` on the server (using `message` for localized text), never leaking stack traces or internal config. 7. **Reuse existing operation tables**: register new similar admin reads or mutations in `ADMIN_READS` / `ADMIN_ACTIONS` instead of duplicating route and service boilerplate. # DatePicker > An internationalized date picker component. ## Introduction `MDatePicker` is an internationalized date picker built on `@internationalized/date` for timezone and locale handling. It supports single date, date range, and multiple date selection, with button trigger, clearable, and quick preset interactions. > [!NOTE] > See: https://ui.nuxt.com/docs/components/calendar > > Built on Nuxt UI's Calendar component > [!NOTE] > See: https://react-spectrum.adobe.com/internationalized/date/index.html > > Uses the > > @internationalized/date > > library for date handling, ensuring timezone safety and i18n support. ## Usage The default button trigger displays the current date. Click to open the calendar panel and write the selected date to v-model: ```vue ``` ### `range` Date Range `range` mode maintains `start` / `end` dates. `numberOfMonths` can display a dual-month calendar simultaneously: ```vue ``` ### `numberOfMonths` Number of Months `numberOfMonths` controls the number of months displayed side by side in the popover, making cross-month selection easier: ```vue ``` ### `clearable` Clearable `clearable` shows a clear entry when a value is set. Clicking it resets without opening the calendar: ```vue ``` ### `presets` Quick Presets Setting `presets` to `default` automatically generates quick items like "Today", "This Week", "This Month" based on the current mode: ```vue ``` ### `multiple` Multiple Date Selection `multiple` mode saves multiple dates in an array. The button label can dynamically display the number of selected dates: ```vue ``` ### `buttonProps` Trigger Button `buttonProps` is passed to the trigger button, allowing adjustment of label, color, variant, and icon: ```vue ``` ## Examples ### Inheriting Field Context When placed inside `UFormField`, it inherits `size` and error state, and the trigger button renders according to the form state: ```vue [ComponentsDatePickerFormFieldExample.vue] ``` ### Inside `UFieldGroup` When placed alongside a button inside `UFieldGroup`, they share size and border connection — ideal for filter bars with shortcut actions: ```vue [ComponentsDatePickerFieldGroupExample.vue] ``` ### Constraining Selectable Date Boundaries `minValue` and `maxValue` disable dates outside the boundary, restricting selection to future or past dates respectively: ```vue [ComponentsDatePickerValidationExample.vue] ``` ### Disabling Dates by Rule `isDateUnavailable` disables dates according to business rules (e.g., weekends as shown in the example): ```vue [ComponentsDatePickerUnavailableExample.vue] ``` ### Custom Trigger Button Label `labelFormat` receives formatting utilities and the current value to combine date and weekday info into the button label: ```vue [ComponentsDatePickerFormatExample.vue] ``` ### Custom Quick Presets Passing an array to `presets` allows business-rule-based date returns. Each item's `value` is a function that receives a `formatter`: ```vue [ComponentsDatePickerPresetsExample.vue] ``` ## useDateFormatter ### Usage Use the auto-imported `useDateFormatter` composable for date formatting, conversion and manipulation, built on the `@internationalized/date` library for internationalized date handling. ```vue ``` - `useDateFormatter` provides locale-aware date formatting based on `Intl.DateTimeFormat`. - Supports bulk conversion of single dates, date ranges, date arrays and nested objects. - Specify a timezone via the `timeZone` option (defaults to the local timezone); identifiers follow the IANA timezone database specification. > [!NOTE] > > All formatting and conversion methods have built-in error handling: passing > > null > > or > > undefined > > returns an empty string or > > null > > without throwing an exception. ### Capabilities at a Glance The table below covers the output shapes of `useDateFormatter` across common date scenarios: ```vue [ComposablesUseDateFormatterOverviewExample.vue] ``` ### Integration with AutoForm When using date fields in AutoForm, use `convertToISO()` for bulk conversion before submitting: ```vue ``` > [!NOTE] > > convertToISO > > automatically traverses all nested date fields while preserving the object structure — no manual conversion required. ### API #### useDateFormatter() `useDateFormatter(options?: DateFormatterOptions): DateFormatter`{lang="ts-type"} Creates a date formatter instance. ##### Parameters **options** (`DateFormatterOptions`): Date formatter configuration options.Locale. Defaults to the enclosing UApp locale, or 'en' outside a component.Date format options, following the Intl.DateTimeFormat specification. Defaults to { dateStyle: 'medium' }.Timezone identifier (e.g. 'Asia/Shanghai', 'America/New_York'). Defaults to the local timezone. See the @internationalized/date timezone docs. ##### Returns Returns a date formatter object with the following methods and properties. #### Formatting Methods **format()** (`(date: DateValue | undefined | null) => string`): Format a single date as a localized string.formatter.format(date) // "Nov 29, 2025" **formatRange()** (`(start: DateValue | undefined | null, end: DateValue | undefined | null, separator?: string) => string`): Format a date range. Default separator is ' - '.formatter.formatRange(startDate, endDate) // "Nov 1, 2025 - Nov 30, 2025" formatter.formatRange(startDate, endDate, ' to ') // "Nov 1, 2025 to Nov 30, 2025" **formatArray()** (`(dates: DateValue[] | undefined | null, separator?: string) => string`): Format an array of dates. Default separator is ', '.formatter.formatArray([date1, date2, date3]) // "Nov 1, 2025, Nov 15, 2025, Nov 29, 2025" #### Conversion Methods **toISO()** (`(date: DateValue | undefined | null) => string`): Convert to an ISO 8601 string.formatter.toISO(date) // "2025-11-29" **toDate()** (`(date: DateValue | undefined | null) => Date | null`): Convert to a JavaScript Date object. **toTimestamp()** (`(date: DateValue | undefined | null) => number | null`): Convert to a timestamp (milliseconds).formatter.toTimestamp(date) // 1732838400000 **toUnixTimestamp()** (`(date: DateValue | undefined | null) => number | null`): Convert to a Unix timestamp (seconds).formatter.toUnixTimestamp(date) // 1732838400 **parse()** (`(value: string) => DateValue | null`): Parse an ISO 8601 date string. Automatically identifies CalendarDate, CalendarDateTime or ZonedDateTime.formatter.parse('2025-11-29') // CalendarDate formatter.parse('2025-11-29T10:30:00') // CalendarDateTime formatter.parse('2025-11-29T10:30:00[Asia/Shanghai]') // ZonedDateTime #### Utility Methods — Getting Dates **getToday()** (`() => CalendarDate`): Get today's date. **getNow()** (`() => ZonedDateTime`): Get the current date and time. **getStartOfWeek()** (`(date: DateValue) => DateValue`): Get the start of the week (based on the current locale). **getEndOfWeek()** (`(date: DateValue) => DateValue`): Get the end of the week (based on the current locale). **getStartOfMonth()** (`(date: DateValue) => DateValue`): Get the start of the month. **getEndOfMonth()** (`(date: DateValue) => DateValue`): Get the end of the month. **getStartOfYear()** (`(date: DateValue) => DateValue`): Get the start of the year. **getEndOfYear()** (`(date: DateValue) => DateValue`): Get the end of the year. #### Utility Methods — Queries **getDayOfWeek()** (`(date: DateValue) => number`): Get the day of the week as a number (0–6, where 0 is the localized first day of the week). **getDayOfWeekName()** (`(date: DateValue, style?: 'narrow' | 'short' | 'long') => string`): Get the localized name of the day of the week.ParametersDate object.Format style. Defaults to long.'narrow' — Shortest format, e.g. "M"'short' — Short format, e.g. "Mon"'long' — Full format, e.g. "Monday"const date = formatter.getToday() formatter.getDayOfWeekName(date, 'narrow') // "M" formatter.getDayOfWeekName(date, 'short') // "Mon" formatter.getDayOfWeekName(date, 'long') // "Monday" formatter.getDayOfWeekName(date) // "Monday" (default) **getWeeksInMonth()** (`(date: DateValue) => number`): Get the number of weeks in the month. **isWeekday()** (`(date: DateValue) => boolean`): Check whether the date is a weekday. **isWeekend()** (`(date: DateValue) => boolean`): Check whether the date is a weekend day. **isSameDay()** (`(a: DateValue, b: DateValue) => boolean`): Check whether two dates are the same day. **isSameMonth()** (`(a: DateValue, b: DateValue) => boolean`): Check whether two dates are in the same month. **isSameYear()** (`(a: DateValue, b: DateValue) => boolean`): Check whether two dates are in the same year. **isToday()** (`(date: DateValue) => boolean`): Check whether the date is today. **isDateValue()** (`(value: unknown) => value is DateValue`): Type guard: check whether a value is a DateValue. **isDateRange()** (`(value: unknown) => value is DateRange`): Type guard: check whether a value is a DateRange. #### Bulk Conversion Methods **convertData()** (`(data: T, converter: (value: DateValue) => any) => T`): Generic data conversion function. Automatically handles single dates, date ranges, date arrays and nested objects.const converted = formatter.convertData(complexData, formatter.toISO) **convertToISO()** (`(data: T) => T`): Bulk convert to ISO strings. Supports single dates, date ranges, arrays and nested objects.// Single date formatter.convertToISO(date) // "2025-11-29" // Date range formatter.convertToISO({ start: date1, end: date2 }) // { start: "2025-11-01", end: "2025-11-30" } // Date array formatter.convertToISO([date1, date2]) // ["2025-11-01", "2025-11-15"] // Nested object formatter.convertToISO({ createdAt: date1, range: { start: date2, end: date3 } }) // { // createdAt: "2025-11-01", // range: { start: "2025-11-20", end: "2025-11-29" } // } **convertToFormatted()** (`(data: T) => T`): Bulk convert to formatted strings. **convertToDate()** (`(data: T) => T`): Bulk convert to Date objects. #### Configuration Properties **locale** (`string`): The current locale in use. **timeZone** (`string`): The current timezone in use. ### Changelog See commit history for [src/runtime/composables/datePicker.ts](https://github.com/mhaibaraai/movk-nuxt/commits/main/src/runtime/composables/datePicker.ts). ### Calendar Visibility `v-model:open` tracks the popover state. Use the exposed `open()` and `close()` methods to update it. The legacy `popoverProps.open` applies when there is no top-level value. `popoverProps.defaultOpen` initializes uncontrolled state. ```vue [ComponentsDatePickerOpenExample.vue] ``` ## API ### Props ```ts /** * Props for the MDatePicker component */ interface MDatePickerProps { id?: string | undefined; name?: string | undefined; /** * 同时作用于触发按钮与日历,缺省时继承 UFormField / UFieldGroup */ size?: "xs" | "sm" | "md" | "lg" | "xl" | undefined; /** * 日历主色;处于表单错误态时触发按钮显示为 error */ color?: "primary" | "secondary" | "info" | "success" | "warning" | "error" | "important" | "neutral" | undefined; disabled?: boolean | undefined; /** * 未选择时的按钮文本,缺省时依次取 `buttonProps.label`、locale 的 `datePicker.placeholder` */ placeholder?: string | undefined; buttonProps?: ButtonProps | undefined; popoverProps?: PopoverProps

| undefined; /** * @default 'formatted' */ labelFormat?: "iso" | "timestamp" | "unix" | "date" | "formatted" | (formatter: { format: (date: Nullable) => string; formatRange: (start: Nullable, end: Nullable, separator?: string) => string; ... 38 more ...; timeZone: string; }, modelValue: CalendarModelValue<...> | undefined): string | undefined; /** * v-model 投影输出格式 * @default 'date-value' */ valueFormat?: V | undefined; clearable?: boolean | undefined; /** * 快捷预设 */ presets?: "default" | DatePickerPreset[] | undefined; ui?: Record & { content?: SlotClass; arrow?: SlotClass; wrapper?: SlotClass; presets?: SlotClass; presetButton?: SlotClass; calendar?: SlotClass; clearIcon?: SlotClass; } | undefined; /** * 语言区域,缺省时跟随 ``,组件外调用时为 `'en'` */ locale?: string | undefined; /** * 日期格式化选项 */ formatOptions?: Intl.DateTimeFormatOptions | undefined; /** * 时区标识符,默认使用本地时区 */ timeZone?: string | undefined; /** * The element or component this component should render as. * @default 'div' */ as?: any; /** * The type of picker. * - `date` renders a day calendar whose heading can switch to a month then year view. * - `month` renders a standalone month picker. * - `year` renders a standalone year picker. * @default 'date' */ type?: "date" | "month" | "year" | undefined; /** * The icon to use for the next year control. * @default appConfig.ui.icons.chevronDoubleRight */ nextYearIcon?: any; /** * Configure the next year button. * `{ color: 'neutral', variant: 'ghost' }`{lang="ts-type"} */ nextYear?: Omit | undefined; /** * The icon to use for the next month control. * @default appConfig.ui.icons.chevronRight */ nextMonthIcon?: any; /** * Configure the next month button. * `{ color: 'neutral', variant: 'ghost' }`{lang="ts-type"} */ nextMonth?: Omit | undefined; /** * The icon to use for the previous year control. * @default appConfig.ui.icons.chevronDoubleLeft */ prevYearIcon?: any; /** * Configure the prev year button. * `{ color: 'neutral', variant: 'ghost' }`{lang="ts-type"} */ prevYear?: Omit | undefined; /** * The icon to use for the previous month control. * @default appConfig.ui.icons.chevronLeft */ prevMonthIcon?: any; /** * Configure the prev month button. * `{ color: 'neutral', variant: 'ghost' }`{lang="ts-type"} */ prevMonth?: Omit | undefined; /** * Whether to make the heading a button that switches between the day, month and year views. * Has no effect when `type` is `year`. Can be an object to override the button props. * `{ color: 'neutral', variant: 'ghost', block: true }`{lang="ts-type"} * @default true */ viewControl?: boolean | Omit | undefined; /** * @default 'solid' */ variant?: "solid" | "outline" | "soft" | "subtle" | undefined; /** * Whether or not a range of dates can be selected */ range?: R | undefined; /** * Whether or not multiple dates can be selected */ multiple?: M | undefined; /** * Show month controls */ monthControls?: boolean | undefined; /** * Show year controls */ yearControls?: boolean | undefined; defaultValue?: CalendarDefaultValue | undefined; weekNumbers?: boolean | undefined; /** * The default placeholder date */ defaultPlaceholder?: CalendarDate | CalendarDateTime | ZonedDateTime | undefined; /** * When combined with `isDateUnavailable`, determines whether non-contiguous ranges, i.e. ranges containing unavailable dates, may be selected. */ allowNonContiguousRanges?: boolean | undefined; /** * This property causes the previous and next buttons to navigate by the number of months displayed at once, rather than one month */ pagedNavigation?: boolean | undefined; /** * Whether or not to prevent the user from deselecting a date without selecting another date first */ preventDeselect?: boolean | undefined; /** * The maximum number of days that can be selected in a range */ maximumDays?: number | undefined; /** * The day of the week to start the calendar on */ weekStartsOn?: 0 | 1 | 2 | 4 | 5 | 3 | 6 | undefined; /** * The format to use for the weekday strings provided via the weekdays slot prop */ weekdayFormat?: "narrow" | "short" | "long" | undefined; /** * Whether or not to always display 6 weeks in the calendar */ fixedWeeks?: boolean | undefined; /** * The maximum date that can be selected */ maxValue?: CalendarDate | CalendarDateTime | ZonedDateTime | undefined; /** * The minimum date that can be selected */ minValue?: CalendarDate | CalendarDateTime | ZonedDateTime | undefined; /** * The number of months to display at once */ numberOfMonths?: number | undefined; /** * Whether or not the calendar is readonly */ readonly?: boolean | undefined; /** * If true, the calendar will focus the selected day, today, or the first day of the month depending on what is visible when the calendar is mounted */ initialFocus?: boolean | undefined; /** * A function that returns whether or not a date is disabled */ isDateDisabled?: (date: DateValue): boolean | undefined; /** * A function that returns whether or not a date is unavailable */ isDateUnavailable?: (date: DateValue): boolean | undefined; /** * A function that returns whether or not a date is hightable */ isDateHighlightable?: (date: DateValue): boolean | undefined; /** * A function that returns the next page of the calendar. It receives the current placeholder as an argument inside the component. */ nextPage?: (placeholder: DateValue): DateValue | undefined; /** * A function that returns the previous page of the calendar. It receives the current placeholder as an argument inside the component. */ prevPage?: (placeholder: DateValue): DateValue | undefined; /** * Whether or not to disable days outside the current view. */ disableDaysOutsideCurrentView?: boolean | undefined; /** * Which part of the range should be fixed */ fixedDate?: "start" | "end" | undefined; /** * A function that returns whether or not a month is disabled */ isMonthDisabled?: (date: DateValue): boolean | undefined; /** * A function that returns whether or not a month is unavailable */ isMonthUnavailable?: (date: DateValue): boolean | undefined; /** * A function that returns whether or not a year is disabled */ isYearDisabled?: (date: DateValue): boolean | undefined; /** * A function that returns whether or not a year is unavailable */ isYearUnavailable?: (date: DateValue): boolean | undefined; /** * Number of years to display per page */ yearsPerPage?: number | undefined; modelValue?: FormattedValue | undefined; /** * @default undefined */ open?: boolean | undefined; } ``` ### Emits ```ts /** * Emitted events for the MDatePicker component */ interface MDatePickerEmits { close:prevent: (payload: []) => void; update:modelValue: (payload: [value: FormattedValue]) => void; update:placeholder: (payload: [date: DateValue]) => void; update:validModelValue: (payload: [date: DateRange]) => void; update:startValue: (payload: [date: DateValue | undefined]) => void; update:open: (payload: [value: boolean | undefined]) => void; update:modelValue: (payload: [value: FormattedValue | undefined]) => void; } ``` ### Slots ```ts /** * Slots for the MDatePicker component */ interface MDatePickerSlots { default(): any; content(): any; heading(): any; day(): any; week-day(): any; month-cell(): any; year-cell(): any; leading(): any; trailing(): any; } ``` ## Theme ::component-theme :: ## Changelog See commit history for [src/runtime/components/DatePicker.vue](https://github.com/mhaibaraai/movk-nuxt/commits/main/src/runtime/components/DatePicker.vue). # MessageBox > A modal message dialog offering both declarative and programmatic usage. ## Introduction `MMessageBox` is a modal dialog component designed for important notifications or scenarios requiring explicit user confirmation. It offers `alert` and `confirm` modes, six built-in semantic types, and programmatic invocation via `useMessageBox()`. > [!NOTE] > See: https://ui.nuxt.com/docs/components/modal > > Built on Nuxt UI's Modal component ## Usage Place the trigger element in the `default` slot. The component internally manages the open state via `UModal`: ```vue ``` ### `mode` Mode `alert` shows only a confirm button; `confirm` provides both cancel and confirm buttons, returning a boolean result: ```vue ``` ### `type` Type `type` affects the default icon and confirm button color, with six semantic values: ```vue ``` ### `icon` Icon `icon` overrides the default icon from `type`. Pass any Iconify icon name: ```vue ``` ### `label` Button Labels `alertConfirmLabel` controls the `alert` mode button label. `confirmLabel` and `cancelLabel` override the two buttons in `confirm` mode respectively: ```vue ``` ### `buttonProps` Button Properties `confirmButton` and `cancelButton` accept full `ButtonProps`, allowing customization of icon, color, variant, and label: ```vue ``` ### `dismissible` Close Strategy `dismissible` defaults to `false` (strict mode). When enabled, clicking the overlay or pressing Esc closes the dialog and marks it as unconfirmed via `close(false)`: ```vue ``` ## Examples ### Controlled State Use `v-model:open` to control the open state externally — ideal for programmatic triggering and multi-button coordination: ```vue [ComponentsMessageBoxControlledExample.vue] ``` ### Body Slot The `body` slot renders rich text content. The `close` slot parameter allows programmatically closing the dialog from within the body: ```vue [ComponentsMessageBoxBodySlotExample.vue] ``` ### Title Slot The `title` slot fully takes over the title area, replacing the default icon-plus-text combination: ```vue [ComponentsMessageBoxTitleSlotExample.vue] ``` ### Description Slot The `description` slot supports rich text descriptions and works alongside the `title` prop: ```vue [ComponentsMessageBoxDescriptionSlotExample.vue] ``` ### Header Slot The `header` slot fully takes over the title and description container, enabling custom layout and typography: ```vue [ComponentsMessageBoxHeaderSlotExample.vue] ``` ### Footer Slot The `footer` slot fully takes over the button area. The `close` slot parameter is used to close the dialog: ```vue [ComponentsMessageBoxFooterSlotExample.vue] ``` ### Close Button Slot The `close` slot customizes the top-right close button — change icon, color, and styles: ```vue [ComponentsMessageBoxCloseSlotExample.vue] ``` ### Content Slot The `content` slot replaces the entire header / body / footer layout — ideal for fully custom scenarios: ```vue [ComponentsMessageBoxContentSlotExample.vue] ``` ### Programmatic Usage Use `useMessageBox()` to invoke dialogs from any logic without declaring the component in templates. `alert()` returns `Promise`, and `confirm()` returns `Promise`: ```vue [ComponentsMessageBoxProgrammaticExample.vue] ``` ## useMessageBox ### Introduction `useMessageBox` provides an imperative dialog API — pop up dialogs without declaring a component in the template. It is built on the [`MessageBox`](https://nuxt.mhaibaraai.me/en/docs/components/message-box) component and Nuxt UI's `useOverlay`. ```ts const { alert, confirm } = useMessageBox() ``` Both methods accept the props of `MessageBox` (`mode` is set automatically by the method): `title`, `description`, `type`, `icon`, button configuration, etc. See the component documentation for the full list. ### alert `alert(options)` opens an alert box with only a confirm action. It returns a Promise that resolves after the user closes the dialog — suitable for blocking notifications: ```ts const { alert } = useMessageBox() async function onSave() { await save() await alert({ type: 'success', title: 'Saved successfully' }) // Continues after the user closes the dialog } ``` ```vue [ComposablesUseMessageBoxAlertExample.vue] ``` ### confirm `confirm(options)` returns `Promise`, mapping confirm/cancel to a boolean value: ```ts const { confirm } = useMessageBox() async function onDelete() { const ok = await confirm({ type: 'warning', title: 'Confirm Delete', description: 'This action cannot be undone. Are you sure you want to continue?' }) if (!ok) return await remove() } ``` ```vue [ComposablesUseMessageBoxConfirmExample.vue] ``` ### Async Confirmation Flow `confirm` is well-suited for chaining async flows — execute the time-consuming task only after confirmation: ```vue [ComposablesUseMessageBoxAsyncExample.vue] ``` > [!TIP] > See: /en/docs/components/message-box > > See the MessageBox component documentation for declarative usage and the full props reference. ## API ### Props ```ts /** * Props for the MMessageBox component */ interface MMessageBoxProps { /** * 模态框标题文本,缺省时取 locale 的 `messageBox.title`。 */ title?: string | undefined; /** * 控制消息框的语义类型。 * 会影响默认图标与确认按钮颜色。 * @default 'primary' */ type?: "primary" | "info" | "success" | "warning" | "error" | "neutral" | undefined; /** * 标题前展示的图标名称,缺省时按 `type` 取对应图标。 */ icon?: any; /** * 控制消息框的操作模式。 * `alert` 仅显示确认按钮,`confirm` 显示取消与确认按钮。 * @default 'alert' */ mode?: "alert" | "confirm" | undefined; /** * 当 `false` 时,点击遮罩层或按下 `Esc` 键将不会关闭模态框。 * @default false */ dismissible?: boolean | undefined; /** * alert 模式下的确认按钮文本,缺省时取 locale 的 `messageBox.acknowledge`。 */ alertConfirmLabel?: string | undefined; /** * 确认按钮文本,缺省时取 locale 的 `messageBox.confirm`。 */ confirmLabel?: string | undefined; /** * 取消按钮文本,缺省时取 locale 的 `messageBox.cancel`。 */ cancelLabel?: string | undefined; /** * 透传给确认按钮的属性。 * 未显式指定 `color` 时会默认继承当前 `type`。 */ confirmButton?: ButtonProps | undefined; /** * 透传给取消按钮的属性。 * 仅在 `mode='confirm'` 时渲染。 */ cancelButton?: ButtonProps | undefined; ui?: Record & { overlay?: SlotClass; content?: SlotClass; header?: SlotClass; wrapper?: SlotClass; body?: SlotClass; footer?: SlotClass; title?: SlotClass; description?: SlotClass; close?: SlotClass; icon?: SlotClass; } | undefined; description?: string | undefined; /** * The content of the modal. */ content?: Omit & Partial> | undefined; /** * Render an overlay behind the modal. * @default true */ overlay?: boolean | undefined; /** * When `true`, enables scrollable overlay mode where content scrolls within the overlay. * @default false */ scrollable?: boolean | undefined; /** * Animate the modal when opening or closing. * @default true */ transition?: boolean | undefined; /** * When `true`, the modal will take up the full screen. * @default false */ fullscreen?: boolean | undefined; /** * Render the modal in a portal. * @default true */ portal?: string | false | true | HTMLElement | undefined; /** * Display a close button to dismiss the modal. * `{ size: 'md', color: 'neutral', variant: 'ghost' }`{lang="ts-type"} * @default true */ close?: boolean | Omit | undefined; /** * The icon displayed in the close button. * @default appConfig.ui.icons.close */ closeIcon?: any; /** * The modality of the dialog When set to `true`,
* interaction with outside elements will be disabled and only dialog content will be visible to screen readers. */ modal?: boolean | undefined; /** * When set to `false`, the dialog content will not be unmounted when closed, but instead hidden with CSS.
* Useful for SEO or when you want to improve performance by not remounting the component on every open. * @default true */ unmountOnHide?: boolean | undefined; open?: boolean | undefined; } ``` ### Emits ```ts /** * Emitted events for the MMessageBox component */ interface MMessageBoxEmits { update:open: (payload: [value: boolean | undefined]) => void; close: (payload: [confirmed: boolean]) => void; } ``` ### Slots ```ts /** * Slots for the MMessageBox component */ interface MMessageBoxSlots { default(): any; content(): any; header(): any; title(): any; description(): any; actions(): any; close(): any; body(): any; footer(): any; } ``` ## Theme ::component-theme :: ## Changelog See commit history for [src/runtime/components/MessageBox.vue](https://github.com/mhaibaraai/movk-nuxt/commits/main/src/runtime/components/MessageBox.vue). # Tree > A tree component built on Nuxt UI Tree, adding search, lazy loading, toolbar, checkboxes, and parent/child strategy. ## Introduction `MTree` is a thin wrapper over Nuxt UI `Tree`, fully passing through all its props, events, and slots while adding several enhancements: search filtering with highlight, async lazy loading, a toolbar (expand/collapse toggle, tri-state select all), checkbox multi-select with parent/child strategy (cascade / isolated), key binding (`v-model:selectedKeys`), an imperative API, and selection categorization. Tree data normalization, filtering, and traversal reuse the `Tree` utility methods from `@movk/core`. > [!NOTE] > See: https://ui.nuxt.com/docs/components/tree > > Built on Nuxt UI's Tree component — all native props and slots are fully passed through ## Usage Pass `items` to render a hierarchical structure. Node `defaultExpanded` controls the initial expansion, and `v-model` binds the selected node: ```vue ``` ### `defaultExpanded` Default Expansion `defaultExpanded` derives the initially expanded parent nodes from a strategy, falling back to the node's own `defaultExpanded` flag. Pass `true` to expand all parents, a `number` to expand only parents with depth less than that value, or a function for custom logic per node and depth: ```vue ``` ### `searchable` Search Filtering `searchable` renders a search input at the top, prunes the tree by keyword while preserving ancestor chains for matching nodes. `highlight` is enabled by default, highlighting matched text and auto-expanding on match. `filter` allows a custom match predicate. `search` supports `v-model:search` two-way binding of the keyword: ```vue ``` ### `checkable` Checkbox Cascade `checkable` renders a checkbox before each node, internally enables `multiple` with parent/child cascade and indeterminate state bubbling. `v-model` collects the selected node array. Checkboxes coexist with node `icon` and parent folder icons: ```vue ``` > [!NOTE] > > checkable > > is syntactic sugar for > > multiple > > + > > strategy > > (default > > cascade > > ). Use > > multiple > > instead when you need multi-select without rendering checkboxes. ### `multiple` Multiple Selection `multiple` enables multi-select without rendering checkboxes. Clicking a node accumulates the selection. `v-model` collects the selected node array: ```vue ``` ### `strategy` Parent/Child Strategy `strategy` controls the parent/child check relationship in multi-select / `checkable` mode. `cascade` (default) cascades parent/child and re-fills the parent when all children are selected. `isolated` keeps parent and child independent — indeterminate state does not bubble: ```vue ``` ### `selectedKeys` Key Binding `selectedKeys` two-way binds the selection using an array of node keys — useful for re-populating from the backend or syncing with routes. `v-model:selectedKeys` and `v-model` are interoperable. Keys are derived from `getKey` / `labelKey`: ```vue ``` ### `toolbar` Toolbar `toolbar` renders a top toolbar with expand/collapse toggle buttons. When `searchable` is set, it embeds a clearable search input. When `checkable` is set, it adds a tri-state select-all checkbox and selection count: ```vue ``` > [!NOTE] > > The toolbar's select-all count is based on > > leaves > > : in cascade mode, selecting a parent brings in child keys. Counting by leaves avoids double counting. ### `lazy` Async Lazy Loading `lazy` works with `loadChildren` — expanding an unloaded parent node fetches child nodes and displays a loading state. The `isLeaf` flag on a node marks it as a leaf, preventing expansion placeholder rendering: ```vue [ComponentsTreeLazyExample.vue] ``` ### `childrenKey` Field Mapping `childrenKey` normalizes the backend's child node field to `children`. `labelKey` specifies the display field, eliminating the need to pre-transform data structures: ```vue ``` ### `labelKey` Dot-Path Value Extraction `labelKey` specifies the node display field, supporting dot-path deep extraction of nested fields like `meta.title`. Key derivation, search, and highlight all use the same path: ```vue ``` > [!NOTE] > > The dot-path must align with UTree's internal value extraction. Only dot notation ( > > a.b.c > > ) is supported — bracket notation ( > > a[0].b > > ) is not. ### `virtualize` Virtual Scrolling `virtualize` passes through Nuxt UI Tree's virtualization capability, rendering only visible nodes — suitable for large data sets: ```vue [ComponentsTreeVirtualizeExample.vue] ``` ### `color` Primary Color `color` passes through Nuxt UI Tree's primary color, applying to selected node text color and keyboard focus ring. The example pre-selects a node for visual reference: ```vue ``` > [!NOTE] > > UTree's > > color > > only applies to selected node text and focus ring. No visible change occurs when no node is selected. Single-color icons (e.g., lucide) inherit the text color; multi-color icons (e.g., vscode-icons) maintain their own coloring. ### `trailingIcon` Trailing Icon `trailingIcon` replaces the expand indicator icon at the end of parent nodes (default `i-lucide-chevron-down`). `item.trailingIcon` on node data takes higher priority: ```vue ``` ### `expandedIcon` Expand Icon `expandedIcon` / `collapsedIcon` customize the leading icon for parent nodes when expanded / collapsed (default `i-lucide-folder-open` / `i-lucide-folder`): ```vue ``` > [!NOTE] > > item.icon > > on a node takes higher priority than > > expandedIcon > > / > > collapsedIcon > > . Therefore, folders that need to switch icons based on expanded state should not set > > item.icon > > . ### `disabled` Disabled `disabled` disables the entire tree, blocking click events on nodes, toolbar controls, and checkboxes for expand, collapse, and select operations. Per-node `item.disabled` disables that node and its entire subtree — freezing expansion state and disabling checkboxes within the subtree: ```vue ``` > [!NOTE] > > Imperative API methods ( > > expandToDepth > > , > > selectAll > > , etc.) are explicit calls and are not affected by > > disabled > > . > > disabled > > only intercepts user clicks and toolbar interactions. ## Examples ### Custom Node Customize node content via passed-through slots like `item-trailing`. Uncovered slots are still rendered by Nuxt UI Tree's defaults: ```vue [ComponentsTreeSlotExample.vue] ``` ### Custom Toolbar `toolbar-leading` / `toolbar-trailing` append content to the start/end of the default toolbar. Use the `#toolbar` slot for full control — its scope exposes methods and state like `toggleExpand`, `selectAll`, `clear`, and `selectionSummary`: ```vue [ComponentsTreeCustomToolbarExample.vue] ``` ### Imperative Control Obtain the component instance via `useTemplateRef` and call methods like `expandToDepth`, `collapseAll`, `selectAll`, and `clearSelection` to control the tree: ```vue [ComponentsTreeImperativeExample.vue] ``` ### Selection Categorization The instance's reactive `treeSelection` returns selection categories: `leaves` (selected leaves), `parents` (fully selected parents), `halfSelected` (indeterminate parents), and `strictlyChecked` (excludes children selected via parent cascade): ```vue [ComponentsTreeSelectionExample.vue] ``` ### Remote Search and Reload `searchMethod` returns matching nodes and `searchDebounce` defaults to 300 ms. Selected nodes persist across searches. Users can retry failures and `searchError` provides the term and error. `reload(key)` refreshes a lazy branch and `reload()` rebuilds from `items`. `getNode(key)` also finds current or still-selected remote nodes. The `leaf` strategy classifies selection by leaves. ```vue [ComponentsTreeRemoteSearchExample.vue] ``` ## API ### Props ```ts /** * Props for the MTree component */ interface MTreeProps { /** * 树数据源,按 childrenKey 解析层级 */ items?: T | undefined; /** * 取子节点数组的字段名,归一化为 UTree 的 children * @default 'children' */ childrenKey?: string | undefined; /** * 展示字段名 * @default 'label' */ labelKey?: keyof Extract, object> & string | DotPathKeys, object>> | undefined; /** * 自定义节点 key,缺省取 labelKey 字段值 */ getKey?: (val: T[number]): string | undefined; /** * 初始展开策略,缺省回退节点上的 defaultExpanded 标记 * - true 展开全部父级 * - number 展开 depth 小于该值的父级 * - 函数 按节点与深度自定义 */ defaultExpanded?: number | false | true | (node: T[number], depth: number): boolean | undefined; /** * 选中节点 key 列表,可用 v-model:selectedKeys 双向绑定 */ selectedKeys?: string[] | undefined; /** * 开启多选 */ multiple?: M | undefined; /** * 多选 / checkable 下的父子勾选策略 * - 'cascade' 父子级联(propagateSelect + bubbleSelect) * - 'isolated' 父子互不关联 * - 'leaf' 交互同 cascade,`change` 与 `treeSelection` 以叶子为准 * @default 'cascade' */ strategy?: "cascade" | "isolated" | "leaf" | undefined; /** * 选中父节点时级联选中子节点。cascade 策略下默认开启,显式 true 可在 isolated 下强制开启;关闭级联请用 strategy='isolated' */ propagateSelect?: boolean | undefined; /** * 子节点全部选中时回填父节点。cascade 策略下默认开启,显式 true 可在 isolated 下强制开启;关闭级联请用 strategy='isolated' */ bubbleSelect?: boolean | undefined; /** * 尺寸 * @default 'md' */ size?: "md" | "xs" | "sm" | "lg" | "xl" | undefined; /** * 主色 * @default 'primary' */ color?: "primary" | "secondary" | "info" | "success" | "warning" | "error" | "important" | "neutral" | undefined; /** * 父节点展开时的图标 * @default 取 app.config 的 ui.icons.folderOpen */ expandedIcon?: any; /** * 父节点折叠时的图标 * @default 取 app.config 的 ui.icons.folder */ collapsedIcon?: any; /** * 禁用整棵树,阻断点击、工具栏与复选框的展开、折叠、选中 */ disabled?: boolean | undefined; /** * 开启顶部搜索过滤 */ searchable?: boolean | undefined; /** * 自定义匹配谓词,缺省按 labelKey 文本不区分大小写包含匹配 */ filter?: (node: T[number], term: string): boolean | undefined; /** * 远程搜索:返回命中的节点树,设置后忽略 `filter` */ searchMethod?: (term: string): Promise | undefined; /** * 远程搜索的防抖时长(ms) * @default 300 */ searchDebounce?: number | undefined; /** * 高亮命中文本,仅在 searchable 时生效 * @default true */ highlight?: boolean | undefined; /** * 开启异步懒加载子节点 */ lazy?: boolean | undefined; /** * 懒加载回调,展开未加载的父节点时调用 */ loadChildren?: (node: T[number]): Promise | undefined; /** * 开启顶部工具栏(展开/折叠,checkable 时附带全选/清空) */ toolbar?: boolean | undefined; /** * 渲染复选框并启用多选(multiple + strategy,默认 cascade) */ checkable?: M | undefined; ui?: Record & { root?: SlotClass; item?: SlotClass; listWithChildren?: SlotClass; itemWithChildren?: SlotClass; link?: SlotClass; linkLeadingIcon?: SlotClass; linkLabel?: SlotClass; linkTrailing?: SlotClass; linkTrailingIcon?: SlotClass; container?: SlotClass; toolbar?: SlotClass; toolbarButton?: SlotClass; search?: SlotClass; checkbox?: SlotClass; highlight?: SlotClass; loading?: SlotClass; loadingIcon?: SlotClass; empty?: SlotClass; } | undefined; /** * The element or component this component should render as. * @default 'ul' */ as?: any; /** * The icon displayed on the right side of a parent node. * @default appConfig.ui.icons.chevronDown */ trailingIcon?: any; /** * The controlled value of the Tree. Can be bind as `v-model`. */ modelValue?: M extends true ? T[number][] : T[number] | undefined; /** * The value of the Tree when initially rendered. Use when you do not need to control the state of the Tree. */ defaultValue?: M extends true ? T[number][] : T[number] | undefined; /** * Use nested DOM structure (children inside parents) vs flattened structure (all items at same level). * When `virtualize` is enabled, this is automatically set to `false`. * @default true */ nested?: boolean | undefined; /** * Enable virtualization for large lists. * Note: when enabled, the tree structure is flattened like if `nested` was set to `false`. * @default false */ virtualize?: boolean | { overscan?: number | undefined; estimateSize?: number | ((index: number) => number) | undefined; } | undefined; onSelect?: (e: SelectEvent, item: T[number]): void | undefined; onToggle?: (e: ToggleEvent, item: T[number]): void | undefined; /** * The controlled value of the expanded item. Can be binded with `v-model`. * @default [] */ expanded?: string[] | undefined; /** * How multiple selection should behave in the collection. */ selectionBehavior?: "replace" | "toggle" | undefined; /** * When `true`, keyboard navigation will loop from last item to first, and vice versa. */ loop?: boolean | undefined; /** * @default '' */ search?: string | undefined; } ``` ### Emits ```ts /** * Emitted events for the MTree component */ interface MTreeEmits { update:modelValue: (payload: [val: M extends true ? T[number][] : T[number]]) => void; update:expanded: (payload: [val: string[]]) => void; update:search: (payload: [value: string]) => void; loadError: (payload: [node: T[number], error: unknown]) => void; searchError: (payload: [term: string, error: unknown]) => void; change: (payload: [payload: { value: (M extends true ? T[number][] : T[number]) | undefined; keys: string[]; selection: TreeSelectionResult; }]) => void; update:modelValue: (payload: [value: (M extends true ? T[number][] : T[number]) | undefined]) => void; update:selectedKeys: (payload: [value: string[] | undefined]) => void; } ``` > [!TIP] > > In addition to passing through Nuxt UI Tree's `update:modelValue` and `update:expanded`, `MTree` additionally provides: > > - `update:search`: Fires when the search keyword changes, supports `v-model:search`. > - `update:selectedKeys`: Fires when the selected key list changes, supports `v-model:selectedKeys`. > - `change`: Fires when the selection changes. Payload is `{ value, keys, selection }`. `keys` is derived from `getKey`/`labelKey`. `selection` is the selection categorization result. ### Slots ```ts /** * Slots for the MTree component */ interface MTreeSlots { item-wrapper(): any; item(): any; item-leading(): any; item-label(): any; item-trailing(): any; toolbar(): any; /** * 默认工具栏起始处追加内容 */ toolbar-leading(): any; /** * 默认工具栏末尾追加内容 */ toolbar-trailing(): any; empty(): any; loading(): any; } ``` ### Expose You can access the typed component instance via [`useTemplateRef`](https://vuejs.org/api/composition-api-helpers.html#usetemplateref). | Name | Type | | --- | --- | | `expandAll()` | `void`
Expand all expandable nodes | | `collapseAll()` | `void`
Collapse all nodes | | `expandToDepth(depth)` | `void`
Expand to the specified depth. `depth=0` collapses all | | `selectAll()` | `void`
Select all selectable nodes | | `clearSelection()` | `void`
Clear all selections | | `treeSelection` | `TreeSelectionResult`
Current selection categorization (`selected` / `leaves` / `parents` / `halfSelected` / `strictlyChecked`) | ## Theme ::component-theme :: ## Changelog See commit history for [src/runtime/components/Tree.vue](https://github.com/mhaibaraai/movk-nuxt/commits/main/src/runtime/components/Tree.vue). # Movk Nuxt > Build Nuxt and Vue apps with schema-driven forms, configurable data tables, reusable components, and composables. Nuxt mode also includes API integration. ::home :: ## Resources for Agents - [API catalog: every service document this site publishes](https://nuxt.mhaibaraai.me/.well-known/api-catalog) - [Sitemap (XML)](https://nuxt.mhaibaraai.me/sitemap.xml) - [Sitemap (Markdown): every page on the site](https://nuxt.mhaibaraai.me/sitemap.md) - [MCP server card: MCP endpoint at https://nuxt.mhaibaraai.me/mcp](https://nuxt.mhaibaraai.me/.well-known/mcp/server-card.json) - [MCP endpoint (streamable HTTP)](https://nuxt.mhaibaraai.me/mcp) - [llms.txt: index of the documentation for LLMs](https://nuxt.mhaibaraai.me/llms.txt) - [llms-full.txt: the full documentation as a single file](https://nuxt.mhaibaraai.me/llms-full.txt) - [Agent skills index: every skill published by this site](https://nuxt.mhaibaraai.me/.well-known/skills/index.json) - [Agent skill: movk-nuxt](https://nuxt.mhaibaraai.me/.well-known/skills/movk-nuxt/SKILL.md) - [Documentation](https://nuxt.mhaibaraai.me/docs) - [Homepage](https://nuxt.mhaibaraai.me/raw/index.md)