← 返回主文档
📋 功能描述
创建 Vue 单文件组件 (.vue),定义物料组件在画布和运行时的实际渲染内容。这是用户在页面设计器中拖拽后看到的视觉效果,也是最终用户在使用低代码页面时看到的 UI 元素。
🧩 模块描述
该组件位于 form-designer 的 widget 目录下,主要职责:
- 画布渲染 - 在页面设计器画布中显示组件预览
- 运行时渲染 - 在最终用户访问页面时渲染实际 UI
- 属性绑定 - 接收来自 Helper buildWidget 生成的 schema props
- 事件处理 - 处理用户交互和组件事件
📁 文件信息
文件路径
packages/form-designer/src/config/widget/<组件名>.vue
组件模式
简单组件直接建 .vue 文件,复杂组件可建目录
所属层级
页面设计器层 (packages/form-designer)
💻 代码示例 - 简单组件
适用于 CommonBtn、CommonTxt 等展示型组件:
<template>
<div class="my-new-component">
{{ displayContent }}
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue'
const props = defineProps<{
content?: string
fontSize?: string
color?: string
}>()
const displayContent = computed(() => {
return props.content || '默认文本'
})
</script>
<style scoped>
.my-new-component {
padding: 8px 16px;
font-size: v-bind(fontSize);
color: v-bind(color);
}
</style>
💻 代码示例 - 复杂组件(目录模式)
适用于 Anchor、CommonTree 等包含子组件和工具函数的复杂组件:
<template>
<div class="anchor-container">
<AnchorIcon />
<ul>
<li v-for="item in anchors" :key="item.id">
{{ item.label }}
</li>
</ul>
</div>
</template>
<script setup lang="ts">
import { useAnchorHooks } from './hooks'
import { DEFAULT_ANCHORS } from './Constant'
const props = defineProps<{
anchors?: Array<{ id: string; label: string }>
}>()
const { anchors } = useAnchorHooks(props.anchors ?? DEFAULT_ANCHORS)
</script>
📝 Props 来源
组件接收的 props 来自 Helper 的 buildWidget() 方法返回的 schema:
{
type: WidgetType.MyNewComponent,
props: {
content: '默认文本',
fontSize: '14px',
color: '#333'
}
}
⚠️ 注意事项
样式隔离
建议使用 <style scoped> 或 CSS Modules,避免全局样式污染。如确需全局样式,使用 :global() 明确声明。
组件设计建议
保持组件简单专注,只负责自身渲染逻辑。复杂业务逻辑应抽取到 composables 或 utils 中。
- 组件名必须与 WidgetType 枚举值保持一致
- 确保组件在没有 props 的情况下也能正常渲染(使用默认值)
- 复杂组件建议拆分到独立目录,便于维护
➡️ 下一步
完成 Vue 组件创建后,继续执行:
- 步骤 3:创建 Helper 配置文件(定义物料面板、属性面板、拖拽行为等)
- 步骤 4:在 RegisterWidget.ts 中注册组件实例