Engine API 参考
VTJ Engine API 参考
本页面为 VTJ Engine 提供了全面的 API 参考,专为需要与核心系统直接交互的高级开发者设计。该引擎由三个基础包组成:@vtj/core(数据模型和协议)、@vtj/renderer(运行时渲染系统)和 @vtj/parser(代码转换工具)。
Engine Architecture Overview
VTJ Engine 遵循分层架构,其中数据模型通过声明式 DSL(领域特定语言)驱动运行时渲染系统。渲染引擎将 DSL 模式转换为 Vue 组件,同时与设计时工具保持双向同步。
graph TD
subgraph Renderer ["@vtj/renderer - Runtime Layer"]
direction TB
PR[Provider]:::orange
LOADER[BlockLoader]
CR[createRenderer]
CTX[Context]:::orange
NR[nodeRender]:::orange
end
subgraph Core ["@vtj/core - Data Layer"]
direction TB
PM[ProjectModel]:::blue
NM[NodeModel]:::blue
BM[BlockModel]:::blue
EM[EventModel]
HM[HistoryModel]
end
subgraph Protocols [Protocol Layer]
direction TB
PS[ProjectSchema]
NS[NodeSchema]
BS[BlockSchema]
TS[Type Definitions]
end
subgraph Parser ["@vtj/parser - Transformation Layer"]
direction TB
VP[VueParser]:::green
UP[UniAppParser]
end
CTX --> PM
CR --> CTX
NR --> NM
PR --> CR
LOADER --> CR
PM --> PS
NM --> NS
BM --> BS
PS <--> VP
BS <--> UP
classDef blue fill:#e1f5ff,stroke:#999
classDef orange fill:#fff4e1,stroke:#999
classDef green fill:#e8f5e9,stroke:#999
Core Models API
ProjectModel
ProjectModel 代表整个低代码项目,包括页面、块、API 和配置。它作为项目级操作的中央协调器。
Constructor
constructor(schema: ProjectSchema)
Key Properties
id: string- 唯一的项目标识符platform: PlatformType- 目标平台('web'、'h5'、'uniapp')pages: PageFile[]- 页面文件定义blocks: BlockFile[]- 块文件定义apis: ApiSchema[]- API 配置dependencies: Dependencie[]- 项目依赖currentFile: PageFile | BlockFile | null- 当前活动文件config: ProjectConfig- 项目配置i18n: I18nConfig- 国际化设置
Methods
update(schema: Partial<ProjectSchema>, silent?: boolean): void- 更新项目属性active(file: PageFile | BlockFile, silent?: boolean): void- 设置当前文件toDsl(version?: string): ProjectSchema- 导出为 DSL 格式isPageFile(file: PageFile | BlockFile): file is PageFile- 类型守卫
Events
EVENT_PROJECT_CHANGE- 项目信息更新时触发EVENT_PROJECT_ACTIVED- 文件更改时触发EVENT_PROJECT_DEPS_CHANGE- 依赖更新时触发EVENT_PROJECT_PAGES_CHANGE- 页面修改时触发EVENT_PROJECT_BLOCKS_CHANGE- 块修改时触发EVENT_PROJECT_APIS_CHANGE- API 修改时触发EVENT_PROJECT_META_CHANGE- 元数据更新时触发EVENT_PROJECT_PUBLISH- 项目发布时触发EVENT_PROJECT_FILE_PUBLISH- 文件发布时触发EVENT_PROJECT_GEN_SOURCE- 代码生成期间触发
NodeModel
NodeModel 表示组件树中的单个 UI 节点(组件或 HTML 元素)。每个节点维护自己的属性、事件、指令和子节点。
Constructor
constructor(schema: NodeSchema, public parent: NodeModel | null = null)
Key Properties
readonly id: string- 唯一的节点标识符readonly name: string- 组件名称或 HTML 标签名readonly from: NodeFrom- 组件来源标识符locked: boolean- 编辑锁定状态invisible: boolean- 可见性标志children: NodeModel[] | string | JSExpression- 子节点slot?: NodeSlot- 插槽放置信息props: Record<string, PropModel>- 节点属性events: Record<string, EventModel>- 事件处理器directives: DirectiveModel[]- Vue 指令
Methods
update(schema: Partial<NodeSchema>, silent?: boolean): void- 更新节点属性setChildren(children: NodeSchema[] | string | JSExpression, silent?: boolean): void- 设置子节点setSlot(slot?: string | NodeSlot, silent?: boolean): void- 设置插槽配置setProp(name: string, value: JSONValue | JSExpression | JSFunction, defaultValue?, silent?: boolean): void- 添加/更新属性removeProp(name: string, silent?: boolean): void- 移除属性getPropValue(name: string): any- 获取属性值findNode(id: string): NodeModel | undefined- 按 ID 搜索节点树dispose(silent?: boolean): void- 销毁节点实例
Events
EVENT_NODE_CHANGE- 任何节点修改时触发
BlockModel
BlockModel 代表一个可复用的组件,具有状态、方法、计算属性、生命周期钩子和数据源。它构成了页面和块的基础。
Constructor
constructor(schema: BlockSchema)
Key Properties
readonly id: string- 唯一的块标识符name: string- 块名称state: BlockState- 响应式状态对象methods: Record<string, JSFunction>- 方法定义computed: Record<string, JSFunction>- 计算属性定义lifeCycles: Record<string, JSFunction>- 生命周期钩子处理器watch: BlockWatch[]- 监听器配置props: Array<string | BlockProp>- Props 定义emits: Array<string | BlockEmit>- Emits 定义inject: BlockInject[]- 依赖注入声明slots: Array<string | BlockSlot>- 插槽定义dataSources: Record<string, DataSourceSchema>- 数据源配置nodes: NodeModel[]- 根节点树css: string- 块样式locked: boolean- 编辑锁定状态
Methods
update(schema: BlockSchema, silent?: boolean): void- 更新块 schematoDsl(version?: string): BlockSchema- 导出为 DSL 格式setFunction(type: 'methods' | 'computed' | 'lifeCycles', name: string, value: JSFunction, silent?: boolean): void- 设置函数属性removeFunction(type: 'methods' | 'computed' | 'lifeCycles', name: string, silent?: boolean): void- 移除函数setState(name: string, value: JSONValue | JSExpression | JSFunction, silent?: boolean): void- 设置状态值removeState(name: string, silent?: boolean): void- 移除状态属性setCss(content: string, silent?: boolean): void- 更新 CSS 内容dispose(): void- 销毁块实例
Node Manipulation
addNode(node: NodeSchema, targetId: string, position: DropPosition, silent?: boolean): void- 将节点添加到树removeNode(id: string, silent?: boolean): void- 从树中移除节点moveNode(id: string, targetId: string, position: DropPosition, silent?: boolean): void- 在树中移动节点cloneNode(id: string, targetId: string, position: DropPosition, silent?: boolean): void- 克隆节点
Events
EVENT_BLOCK_CHANGE- 任何块修改时触发
PropModel & EventModel
PropModel 管理组件属性值,支持静态值、表达式和函数。
constructor(
public name: string,
public value?: JSONValue | JSExpression | JSFunction,
public defaultValue?: JSONValue | JSExpression | JSFunction
)
setValue(value: JSONValue | JSExpression | JSFunction): void
getValue(): any
static toDsl(props: Record<string, PropModel>): NodeProps
static parse(props: NodeProps): Record<string, PropModel>
EventModel 管理包括修饰符在内的事件处理器定义。
constructor(private schema: NodeEvent)
update(schema: Partial<NodeEvent>): void
static toDsl(events: Record<string, EventModel>): NodeEvents
static parse(events: NodeEvents): Record<string, EventModel>
Renderer API
Context
Context 类为 DSL 渲染提供执行环境,管理状态、props、生命周期钩子,并提供对 Vue 实例属性的访问。
Constructor
constructor(options: {
mode: ContextMode,
dsl?: BlockSchema,
attrs?: ContextAttrs
})
Key Properties
__mode: ContextMode- 执行模式(Runtime、Design、VNode、Raw)__id: string | null- 用于作用域的块 ID__instance: any- Vue 组件实例代理state: Record<string, any>- 响应式状态props: Record<string, any>- 组件 props$refs: Record<string, any>- 模板引用$components: Record<string, any>- 可用组件$libs: Record<string, any>- 外部库$apis: Record<string, any>- API 函数$provider: Provider | null- Provider 实例
Methods
setup(attrs: Record<string, any>, Vue?: any): void- 使用 Vue 实例初始化上下文__parseFunction(code?: JSFunction): Function | undefined- 将 JSFunction 解析为可执行函数__parseExpression(code?: JSExpression | JSFunction): any- 在上下文中计算 JSExpression__ref(id: string | null, ref?: string | Function): Function- 创建模板 ref 处理器__clone(context: Record<string, any>): Context- 创建具有合并属性的子上下文
Lifecycle Integration Context 自动与 Vue 生命周期钩子集成:
onMounted- 完成属性代理onUnmounted- 清理引用onBeforeUpdate- 重置缓存的引用
nodeRender
核心渲染函数,将 NodeSchema 转换为 Vue VNode,处理指令、props、事件和插槽。
function nodeRender(
dsl: NodeSchema,
context: Context,
Vue?: any,
loader?: BlockLoader,
brothers?: NodeSchema[],
isBranch?: boolean,
): VNode | VNode[] | null;
Processing Pipeline
- Early Exit - 如果节点不可见或无效则返回 null
- Directive Extraction - 分离 v-if、v-else-if、v-else、v-for、v-show、v-model、v-bind、v-html 和自定义指令
- Conditional Rendering - 处理 v-if/v-else-if/v-else 链
- Component Resolution - 通过加载器加载组件,处理内置组件
- Props & Events - 使用
parseNodeProps解析 props,使用parseNodeEvents解析事件 - Directive Application - 应用 v-show、v-bind、v-html、v-model 指令
- Slot Processing - 使用
childrenToSlots将子节点转换为具名插槽 - VNode Creation - 使用 Vue.createVNode 创建 VNode
- Directive Binding - 使用 Vue.withDirectives 应用剩余的自定义指令
Special Handling
- Built-in Components:
component、slot - v-for Rendering: 创建具有重复渲染的片段
- Conditional Branches: 通过
branchRender处理 v-if/v-else-if/v-else - Scoped CSS: 自动应用
data-v-{id}属性进行样式隔离
createRenderer
工厂函数,从 BlockSchema 创建 Vue 组件,建立响应式状态、计算属性、方法、监听器和生命周期钩子。
function createRenderer(options: {
Vue?: any;
mode?: ContextMode;
dsl?: BlockSchema;
components?: Record<string, any>;
libs?: Record<string, any>;
apis?: Record<string, any>;
loader?: BlockLoader;
window?: Window;
}): {
renderer: DefineComponent;
context: Context;
};
Generated Component Structure
渲染器生成一个 Vue DefineComponent,其中包含:
- Props: 从
BlockSchema.props计算得出,包含类型转换 - Setup Function: 初始化所有响应式系统
- State: 使用
Vue.reactive创建,包含表达式解析 - Computed: 来自 schema 的计算属性,包含函数解析
- Methods: 来自 schema 的方法,包含上下文绑定
- Injects: 使用 Vue.inject 进行依赖注入
- Data Sources: 创建模拟或真实的 API 处理器
- Watches: 从 schema 配置监听器
- Emits: 来自 schema 的事件名称
- Expose: 来自 schema 的公共 API
- Render: 为每个根节点调用
nodeRender - Lifecycle Hooks: 来自 schema 的钩子映射到 Vue 生命周期
Helper Functions
createProps(props, context): 将 props schema 转换为 Vue props 定义createState(Vue, state, context): 创建具有表达式求值的响应式状态createComputed(Vue, computedSchema, context): 创建计算属性createMethods(methods, context): 创建方法函数createInject(Vue, inject, context): 创建依赖注入createDataSources(dataSources, context): 创建数据源处理器setWatches(Vue, watch, context): 配置监听器createLifeCycles(lifeCycles, context): 映射生命周期钩子
BlockLoader
加载器机制将组件名称解析为实际组件,支持多种来源,包括本地组件、远程 schema 和插件。
Type Definition
type BlockLoader = (
name: string,
from?: NodeFrom,
Vue?: any,
) => string | DefineComponent;
Factory Function
function createLoader(options: {
getDsl: (id: string) => Promise<BlockSchema | null>;
getDslByUrl: (url: string) => Promise<BlockSchema | null>;
options: Partial<CreateRendererOptions>;
}): BlockLoader;
Resolution Strategy
- String from: 直接返回组件名称
- Schema type (from.type === 'Schema'): 通过 ID 加载 DSL,使用渲染器创建异步组件
- UrlSchema type (from.type === 'UrlSchema'): 通过 URL 加载 DSL,使用渲染器创建异步组件
- Plugin type (from.type === 'Plugin'): 加载 UMD 库,提取组件
- Fallback: 返回名称字符串
Utility Functions
defaultLoader(name: string): 返回未更改的名称getPlugin(from: NodeFromPlugin, global?): Promise<BlockPlugin | null> - 从 URL 加载插件clearLoaderCache(): 清除所有缓存的组件和排队的请求
Provider
Provider 类是中央运行时协调器,管理项目配置、加载依赖、初始化服务并提供全局 API。
Constructor
constructor(public options: {
service: Service,
project?: Partial<ProjectSchema>,
modules?: Record<string, () => Promise<any>>,
mode?: ContextMode,
adapter?: Partial<ProvideAdapter>,
router?: Router,
dependencies?: Record<string, () => Promise<any>>,
materials?: Record<string, () => Promise<any>>,
libraryOptions?: Record<string, any>,
globals?: Record<string, any>,
materialPath?: string,
nodeEnv?: NodeEnv,
install?: (app: App) => void,
routeAppendTo?: RouteRecordName,
pageRouteName?: string,
routeMeta?: RouteMeta,
enhance?: (app: App, provider: Provider) => void,
vtjDir?: string,
vtjRawDir?: string,
enableStaticRoute?: boolean
})
Key Properties
mode: ContextMode- 当前执行模式service: Service- 核心服务实例project: ProjectSchema | null- 当前项目配置components: Record<string, any>- 已加载的组件library: Record<string, any>- 第三方库globals: Record<string, any>- 全局变量modules: Record<string, () => Promise<any>>- 异步模块加载器dependencies: Record<string, () => Promise<any>>- 依赖加载器materials: Record<string, () => Promise<any>>- 物料加载器adapter: ProvideAdapter- 请求/jsonp 适配器router: Router | null- Vue Router 实例nodeEnv: NodeEnv- 运行时环境
Core Methods
load(project: ProjectSchema): Promise<void>- 加载项目配置createMock(func): Function- 创建模拟数据处理器loadDependencies(deps: Dependencie[]): Promise<void>- 加载项目依赖loadMaterials(materials: Material[]): Promise<void>- 加载物料组件use(app: App): void- 将 provider 安装为 Vue 插件ready(callback: () => void): void- 当 provider 准备就绪时执行回调getDsl(id: string): Promise<BlockSchema | null>- 加载块 DSLgetDslByUrl(url: string): Promise<BlockSchema | null>- 从 URL 加载 DSL
Initialization Process
- 设置模式、服务、路由和路径
- 合并适配器配置
- 如果已配置,则初始化访问控制
- 加载项目 schema(Design 模式除外)
- 创建模拟 API 处理器
- 根据模式加载依赖
- 初始化 i18n、路由和全局变量
Event System
引擎使用基于 mitt 的集中式事件总线进行组件间通信。
Emitter Type
type Emitter = {
on(type: string, listener: (...args: any[]) => void): void;
off(type: string, listener: (...args: any[]) => void): void;
emit(type: string, ...args: any[]): void;
all: { clear(): void };
};
Event Types
| Event | Payload | Description |
|---|---|---|
EVENT_PROJECT_CHANGE | ProjectModelEvent | 项目信息已更新 |
EVENT_PROJECT_ACTIVED | ProjectModelEvent | 当前文件已更改 |
EVENT_PROJECT_DEPS_CHANGE | ProjectModelEvent | 依赖已更新 |
EVENT_PROJECT_PAGES_CHANGE | ProjectModelEvent | 页面已修改 |
EVENT_PROJECT_BLOCKS_CHANGE | ProjectModelEvent | 块已修改 |
EVENT_PROJECT_APIS_CHANGE | ProjectModelEvent | API 已更新 |
EVENT_PROJECT_META_CHANGE | ProjectModelEvent | 元数据已更新 |
EVENT_PROJECT_PUBLISH | ProjectModelEvent | 项目已发布 |
EVENT_PROJECT_FILE_PUBLISH | ProjectModelEvent | 文件已发布 |
EVENT_PROJECT_GEN_SOURCE | ProjectModelEvent | 代码已生成 |
EVENT_BLOCK_CHANGE | BlockModel | 块已修改 |
EVENT_NODE_CHANGE | NodeModel | 节点已修改 |
EVENT_HISTORY_CHANGE | HistoryModelEvent | 历史记录已更新 |
EVENT_HISTORY_LOAD | HistoryModelEvent | 历史记录已加载 |
Usage Example
import { emitter, EVENT_NODE_CHANGE } from "@vtj/core";
// Subscribe to events
emitter.on(EVENT_NODE_CHANGE, (node: NodeModel) => {
console.log("Node changed:", node.id);
});
// Emit events
emitter.emit(EVENT_NODE_CHANGE, nodeModel);
// Cleanup
emitter.all.clear();
Protocol Types & Schemas
Core Protocol Types
JSExpression & JSFunction
interface JSExpression {
type: "JSExpression";
id?: string;
value: string;
}
interface JSFunction {
type: "JSFunction";
id?: string;
value: string;
}
这些类型将 JavaScript 代码包装为字符串,支持在运行时进行动态求值。可选的 id 字段支持在代码生成期间进行代码转换。
PlatformType
type PlatformType = "web" | "h5" | "uniapp";
指定目标部署平台。
VTJConfig
interface VTJConfig {
enhance?: boolean | EnhanceConfig;
extension?: ExtensionConfig;
history?: "hash" | "web";
base?: string;
pageRouteName?: string;
pageBasePath?: string;
__BASE_PATH__?: string;
remote?: string;
auth?: string | (() => Promise<any>);
checkVersion?: boolean;
platform?: PlatformType;
access?: Record<string, any>;
__ACCESS__?: Record<string, any>;
}
VTJ 运行时的全局配置。
Schema Types
NodeSchema
interface NodeSchema {
id?: string;
name: string;
from?: NodeFrom;
locked?: boolean;
invisible?: boolean;
children?: NodeSchema[] | string | JSExpression;
slot?: string | NodeSlot;
props?: NodeProps;
events?: NodeEvents;
directives?: NodeDirective[];
}
定义单个 UI 节点。
BlockSchema
interface BlockSchema {
id?: string;
name?: string;
locked?: boolean;
inject?: BlockInject[];
state?: BlockState;
lifeCycles?: Record<string, JSFunction>;
methods?: Record<string, JSFunction>;
computed?: Record<string, JSFunction>;
watch?: BlockWatch[];
css?: string;
props?: Array<string | BlockProp>;
emits?: Array<string | BlockEmit>;
expose?: string[];
slots?: Array<string | BlockSlot>;
dataSources?: Record<string, DataSourceSchema>;
nodes?: NodeSchema[];
__VTJ_BLOCK__?: boolean;
__VERSION__?: string;
__TEMPLATE_ID__?: string;
transform?: Record<string, string>;
}
定义具有完整 Vue 组件功能的可复用组件。
ProjectSchema
interface ProjectSchema {
__VTJ_PROJECT__?: boolean;
id?: string;
__UID__?: string;
locked?: string;
platform?: PlatformType;
name?: string;
description?: string;
homepage?: string;
dependencies?: Dependencie[];
pages?: PageFile[];
blocks?: BlockFile[];
apis?: ApiSchema[];
meta?: MetaSchema[];
config?: ProjectConfig;
uniConfig?: UniConfig;
globals?: GlobalConfig;
i18n?: I18nConfig;
env?: EnvConfig[];
__BASE_PATH__?: string;
}
顶层项目定义。
Service API
Service 抽象类定义了后端交互的契约,提供了对项目、文件和历史记录的 CRUD 操作方法。
Abstract Methods
| Method | Description |
|---|---|
getExtension(): Promise<VTJConfig | undefined> | 获取设计器配置 |
init(project: Partial<ProjectSchema>, isInit?): Promise<ProjectSchema> | 初始化项目 |
saveProject(project: ProjectSchema, type?): Promise<boolean> | 保存项目 |
saveMaterials(project, materials): Promise<boolean> | 保存物料 |
saveFile(file: BlockSchema, project?): Promise<boolean> | 保存文件 |
getFile(id: string, project?): Promise<BlockSchema> | 获取文件 |
removeFile(id: string, project?): Promise<boolean> | 删除文件 |
saveHistory(history, project?): Promise<boolean> | 保存历史记录 |
removeHistory(id: string, project?): Promise<boolean> | 删除历史记录 |
getHistory(id: string, project?): Promise<HistorySchema> | 获取历史记录 |
getHistoryItem(fId: string, id: string, project?): Promise<HistoryItem> | 获取历史记录项 |
saveHistoryItem(fId: string, item, project?): Promise<boolean> | 保存历史记录项 |
removeHistoryItem(fId: string, ids: string[], project?): Promise<boolean> | 删除历史记录项 |
publish(project: ProjectSchema): Promise<boolean> | 发布项目 |
publishFile(project, file): Promise<boolean> | 发布文件 |
genVueContent(project, dsl): Promise<string> | DSL 转 Vue 代码 |
parseVue(project, options): Promise<BlockSchema> | Vue 转 DSL |
createRawPage(file, project?): Promise<boolean> | 创建源页面 |
removeRawPage(id: string, project?): Promise<boolean> | 删除源页面 |
uploadStaticFile(file, projectId): Promise<StaticFileInfo | null> | 上传文件 |
getStaticFiles(projectId): Promise<StaticFileInfo[]> | 获取静态文件 |
removeStaticFile(name, projectId, file?): Promise<boolean> | 删除静态文件 |
clearStaticFiles(projectId): Promise<boolean> | 删除所有静态文件 |
getPluginMaterial(from): Promise<MaterialDescription | null> | 获取插件物料 |
genSource(project: ProjectSchema): Promise<string> | 生成项目 zip |
Parser API
解析器包提供 Vue/UniApp 源代码与 DSL schema 之间的双向转换。
Vue Parser
- 解析 Vue SFC(单文件组件)模板、脚本和样式
- 将 HTML 模板转换为 NodeSchema 树
- 将 JavaScript 代码转换为状态、方法、计算属性和生命周期钩子
- 处理 CSS 样式提取
UniApp Parser
- 支持 UniApp 特定语法和配置
- 处理平台特定的条件编译
- 解析 pages.json 配置
Key Functions
// Vue to DSL
function parseVue(options: ParseVueOptions): Promise<BlockSchema>;
// Template parsing
function parseTemplate(template: string): NodeSchema[];
// Script parsing
function parseScript(script: string): {
state: BlockState;
methods: Record<string, JSFunction>;
computed: Record<string, JSFunction>;
lifeCycles: Record<string, JSFunction>;
watch: BlockWatch[];
};
// Style parsing
function parseStyle(style: string): string;
ContextMode Enumeration
引擎以不同模式运行,这些模式会影响渲染行为和可用功能。
enum ContextMode {
Runtime = "runtime", // Production runtime mode
Design = "design", // Designer mode with drag-drop
VNode = "vnode", // VNode preview mode
Raw = "raw", // Source code mode
}
Mode Characteristics
- Runtime: 完整执行,具有动态表达式求值,支持对代码生成的表达式进行转换映射
- Design: 向 DOM 元素添加可拖动属性,跟踪上下文以进行设计器交互
- VNode: 禁用 ref 分配(返回 undefined),用于预览渲染
- Raw: 直接执行源代码,进行最少的 DSL 处理
Base Class
Base 类为异步初始化提供就绪状态管理。
class Base {
protected listeners: Array<() => void>;
public isReady: boolean;
ready(callback: () => void): void;
resetReady(): void;
protected triggerReady(): void;
}
Usage Pattern
class MyService extends Base {
async initialize() {
// Do async work
await loadSomething();
// Signal ready
this.triggerReady();
}
}
// Consumer
service.ready(() => {
// Execute after service is ready
});
Summary
VTJ Engine 为跨三个层次的低代码应用开发提供了全面的 API:
- Core Layer - 数据模型(ProjectModel、NodeModel、BlockModel),具有事件驱动更新
- Renderer Layer - 运行时执行系统(Context、nodeRender、createRenderer),具有 Vue 集成
- Transformation Layer - 双向代码转换
该架构通过声明式 DSL 实现了设计时工具与运行时执行之间的无缝集成,支持多个平台和渲染模式。
参考资料
- 官方文档:vtj.pro/
- 在线平台:app.vtj.pro/
- 开源仓库:gitee.com/newgateway/…