vue

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

@json-render/vue

@json-render/vue

Vue 3 renderer that converts JSON specs into Vue component trees with data binding, visibility, and actions.
一款Vue 3渲染器,可将JSON规范转换为具备数据绑定、可见性控制和动作处理能力的Vue组件树。

Installation

安装

bash
npm install @json-render/vue @json-render/core zod
Peer dependencies:
vue ^3.5.0
and
zod ^4.0.0
.
bash
npm install @json-render/vue @json-render/core zod
对等依赖:
vue ^3.5.0
zod ^4.0.0

Quick Start

快速开始

Create a Catalog

创建组件目录

typescript
import { defineCatalog } from "@json-render/core";
import { schema } from "@json-render/vue/schema";
import { z } from "zod";

export const catalog = defineCatalog(schema, {
  components: {
    Card: {
      props: z.object({ title: z.string(), description: z.string().nullable() }),
      description: "A card container",
    },
    Button: {
      props: z.object({ label: z.string(), action: z.string() }),
      description: "A clickable button",
    },
  },
  actions: {},
});
typescript
import { defineCatalog } from "@json-render/core";
import { schema } from "@json-render/vue/schema";
import { z } from "zod";

export const catalog = defineCatalog(schema, {
  components: {
    Card: {
      props: z.object({ title: z.string(), description: z.string().nullable() }),
      description: "A card container",
    },
    Button: {
      props: z.object({ label: z.string(), action: z.string() }),
      description: "A clickable button",
    },
  },
  actions: {},
});

Define Registry with h() Render Functions

使用h()渲染函数定义注册中心

typescript
import { h } from "vue";
import { defineRegistry } from "@json-render/vue";
import { catalog } from "./catalog";

export const { registry } = defineRegistry(catalog, {
  components: {
    Card: ({ props, children }) =>
      h("div", { class: "card" }, [
        h("h3", null, props.title),
        props.description ? h("p", null, props.description) : null,
        children,
      ]),
    Button: ({ props, emit }) =>
      h("button", { onClick: () => emit("press") }, props.label),
  },
});
typescript
import { h } from "vue";
import { defineRegistry } from "@json-render/vue";
import { catalog } from "./catalog";

export const { registry } = defineRegistry(catalog, {
  components: {
    Card: ({ props, children }) =>
      h("div", { class: "card" }, [
        h("h3", null, props.title),
        props.description ? h("p", null, props.description) : null,
        children,
      ]),
    Button: ({ props, emit }) =>
      h("button", { onClick: () => emit("press") }, props.label),
  },
});

Render Specs

渲染规范

vue
<script setup lang="ts">
import { StateProvider, ActionProvider, Renderer } from "@json-render/vue";
import { registry } from "./registry";

const spec = { root: "card-1", elements: { /* ... */ } };
</script>

<template>
  <StateProvider :initial-state="{ form: { name: '' } }">
    <ActionProvider :handlers="{ submit: handleSubmit }">
      <Renderer :spec="spec" :registry="registry" />
    </ActionProvider>
  </StateProvider>
</template>
vue
<script setup lang="ts">
import { StateProvider, ActionProvider, Renderer } from "@json-render/vue";
import { registry } from "./registry";

const spec = { root: "card-1", elements: { /* ... */ } };
</script>

<template>
  <StateProvider :initial-state="{ form: { name: '' } }">
    <ActionProvider :handlers="{ submit: handleSubmit }">
      <Renderer :spec="spec" :registry="registry" />
    </ActionProvider>
  </StateProvider>
</template>

Providers

提供者组件

ProviderPurpose
StateProvider
Share state across components (JSON Pointer paths). Accepts
initialState
or
store
for controlled mode.
ActionProvider
Handle actions dispatched via the event system
VisibilityProvider
Enable conditional rendering based on state
ValidationProvider
Form field validation
提供者用途
StateProvider
在组件间共享状态(支持JSON指针路径)。接受
initialState
store
以启用受控模式。
ActionProvider
处理通过事件系统分发的动作
VisibilityProvider
支持基于状态的条件渲染
ValidationProvider
表单字段验证

Composables

组合式函数

ComposablePurpose
useStateStore()
Access state context (
state
as
ShallowRef
,
get
,
set
,
update
)
useStateValue(path)
Get single value from state
useIsVisible(condition)
Check if a visibility condition is met
useActions()
Access action context
useAction(binding)
Get a single action dispatch function
useFieldValidation(path, config)
Field validation state
useBoundProp(propValue, bindingPath)
Two-way binding for
$bindState
/
$bindItem
Note:
useStateStore().state
returns a
ShallowRef<StateModel>
— use
state.value
to access.
组合式函数用途
useStateStore()
访问状态上下文(
state
ShallowRef
类型,包含
get
set
update
方法)
useStateValue(path)
从状态中获取单个值
useIsVisible(condition)
检查可见性条件是否满足
useActions()
访问动作上下文
useAction(binding)
获取单个动作的分发函数
useFieldValidation(path, config)
字段验证状态
useBoundProp(propValue, bindingPath)
$bindState
/
$bindItem
实现双向绑定
注意:
useStateStore().state
返回
ShallowRef<StateModel>
类型,需使用
state.value
访问状态内容。

External Store (StateStore)

外部状态存储(StateStore)

Pass a
StateStore
to
StateProvider
to wire json-render to Pinia, VueUse, or any state management:
typescript
import { createStateStore, type StateStore } from "@json-render/vue";

const store = createStateStore({ count: 0 });
vue
<StateProvider :store="store">
  <Renderer :spec="spec" :registry="registry" />
</StateProvider>
StateStore
传递给
StateProvider
,可将json-render与Pinia、VueUse或任何状态管理库集成:
typescript
import { createStateStore, type StateStore } from "@json-render/vue";

const store = createStateStore({ count: 0 });
vue
<StateProvider :store="store">
  <Renderer :spec="spec" :registry="registry" />
</StateProvider>

Dynamic Prop Expressions

动态属性表达式

Props support
$state
,
$bindState
,
$cond
,
$template
,
$computed
. Use
{ "$bindState": "/path" }
on the natural value prop for two-way binding.
属性支持
$state
$bindState
$cond
$template
$computed
。在原生值属性上使用
{ "$bindState": "/path" }
可实现双向绑定。

Visibility Conditions

可见性条件

typescript
{ "$state": "/user/isAdmin" }
{ "$state": "/status", "eq": "active" }
{ "$state": "/maintenance", "not": true }
[ cond1, cond2 ]  // implicit AND
typescript
{ "$state": "/user/isAdmin" }
{ "$state": "/status", "eq": "active" }
{ "$state": "/maintenance", "not": true }
[ cond1, cond2 ]  // 隐式逻辑与

Built-in Actions

内置动作

setState
,
pushState
,
removeState
, and
validateForm
are built into the Vue schema and handled by
ActionProvider
:
json
{
  "action": "setState",
  "params": { "statePath": "/activeTab", "value": "settings" }
}
setState
pushState
removeState
validateForm
是Vue schema中内置的动作,由
ActionProvider
处理:
json
{
  "action": "setState",
  "params": { "statePath": "/activeTab", "value": "settings" }
}

Event System

事件系统

Components use
emit(event)
to fire events, or
on(event)
for metadata (
shouldPreventDefault
,
bound
).
组件可使用
emit(event)
触发事件,或使用
on(event)
添加元数据(如
shouldPreventDefault
bound
)。

Streaming

流式渲染

useUIStream
and
useChatUI
return Vue Refs for streaming specs from an API.
useUIStream
useChatUI
返回Vue Refs,用于从API流式获取规范。

BaseComponentProps

BaseComponentProps

For catalog-agnostic reusable components:
typescript
import type { BaseComponentProps } from "@json-render/vue";

const Card = ({ props, children }: BaseComponentProps<{ title?: string }>) =>
  h("div", null, [props.title, children]);
用于与目录无关的可复用组件:
typescript
import type { BaseComponentProps } from "@json-render/vue";

const Card = ({ props, children }: BaseComponentProps<{ title?: string }>) =>
  h("div", null, [props.title, children]);

Key Exports

核心导出

ExportPurpose
defineRegistry
Create a type-safe component registry from a catalog
Renderer
Render a spec using a registry
schema
Element tree schema (from
@json-render/vue/schema
)
StateProvider
,
ActionProvider
,
VisibilityProvider
,
ValidationProvider
Context providers
useStateStore
,
useStateValue
,
useBoundProp
State composables
useActions
,
useAction
Action composables
useFieldValidation
,
useIsVisible
Validation and visibility
useUIStream
,
useChatUI
Streaming composables
createStateStore
Create in-memory
StateStore
BaseComponentProps
Catalog-agnostic component props type
导出项用途
defineRegistry
从组件目录创建类型安全的组件注册中心
Renderer
使用注册中心渲染规范
schema
元素树 schema(来自
@json-render/vue/schema
StateProvider
,
ActionProvider
,
VisibilityProvider
,
ValidationProvider
上下文提供者组件
useStateStore
,
useStateValue
,
useBoundProp
状态相关组合式函数
useActions
,
useAction
动作相关组合式函数
useFieldValidation
,
useIsVisible
验证与可见性相关函数
useUIStream
,
useChatUI
流式渲染组合式函数
createStateStore
创建内存中的
StateStore
BaseComponentProps
与目录无关的组件属性类型