This commit is contained in:
wfz
2026-01-20 21:53:09 +08:00
parent 4a90340ab3
commit bfa4e3107f
23 changed files with 2154 additions and 592 deletions

View File

@@ -1,5 +0,0 @@
# Vue 3 + TypeScript + Vite
This template should help get you started developing with Vue 3 and TypeScript in Vite. The template uses Vue 3 `<script setup>` SFCs, check out the [script setup docs](https://v3.vuejs.org/api/sfc-script-setup.html#sfc-script-setup) to learn more.
Learn more about the recommended Project Setup and IDE Support in the [Vue Docs TypeScript Guide](https://vuejs.org/guide/typescript/overview.html#project-setup).

View File

@@ -40,112 +40,20 @@
"id": "right",
"tabs": [
{
"id": "vrh9bl2",
"title": "数据表格",
"id": "09w17vo",
"title": "数据",
"content": "新窗口内容",
"materialId": "DataTable",
"materialState": {
"data": [
{
"property": "项目名称",
"value": "1111"
},
{
"property": "框架",
"value": "9999"
},
{
"property": "语言",
"value": "TypeScript"
},
{
"property": "构建工具",
"value": "Vite"
},
{
"property": "状态管理",
"value": "Pinia"
},
{
"property": "版本",
"value": "1.0.0"
},
{
"property": "作者",
"value": "Developer"
},
{
"property": "许可证",
"value": "MIT"
}
]
}
"materialId": "DataTable"
},
{
"id": "mxfx11j",
"title": "树形展示器",
"id": "vihlzl5",
"title": "结构",
"content": "新窗口内容",
"materialId": "TreeViewer",
"materialState": {
"treeData": [
{
"id": "1",
"label": "项目根目录",
"expanded": true,
"children": [
{
"id": "1-1",
"label": "src",
"expanded": true,
"children": [
{
"id": "1-1-2",
"label": "stores"
},
{
"id": "1-1-4",
"label": "App.vue"
},
{
"id": "1-1-5",
"label": "main.ts"
},
{
"id": "1-1-1",
"label": "components"
}
]
},
{
"id": "1-1-3",
"label": "types"
},
{
"id": "1-2",
"label": "public",
"children": [
{
"id": "1-3",
"label": "package.json"
},
{
"id": "1-2-1",
"label": "favicon.ico"
}
]
},
{
"id": "1-4",
"label": "vite.config.ts"
}
]
}
]
}
"materialId": "TreeViewer"
}
],
"activeTabId": "mxfx11j"
"activeTabId": "09w17vo"
}
},
"lastUpdated": "2026-01-20T11:33:21.385Z"
"lastUpdated": "2026-01-20T13:52:38.363Z"
}

View File

@@ -1,9 +1,42 @@
{
"id": "GridTable",
"name": "表格",
"icon": "📊",
"description": "用于展示数据的表格组件",
"props": {
"rows": 3,
"columns": 3,
"headers": ["列1", "列2", "列3"]
"template": "template.html",
"defaultSpan": 24,
"metadata": {
"span": {
"label": "宽度",
"type": "number",
"min": 1,
"max": 24,
"target": "el-col",
"attr": ":span"
},
"size": {
"label": "尺寸",
"type": "select",
"options": ["", "medium", "small", "mini"],
"target": "el-table",
"attr": "size"
},
"stripe": {
"label": "斑马纹",
"type": "boolean",
"target": "el-table",
"attr": "stripe"
},
"border": {
"label": "边框",
"type": "boolean",
"target": "el-table",
"attr": "border"
},
"columns": {
"label": "列配置",
"type": "columns",
"target": "el-table-column"
}
}
}

View File

@@ -1,63 +0,0 @@
<script setup lang="ts">
import { computed } from 'vue'
const props = defineProps<{
rows?: number
columns?: number
headers?: string[]
}>()
const tableRows = computed(() => props.rows || 3)
const tableCols = computed(() => props.columns || 3)
const tableHeaders = computed(() => props.headers || [])
</script>
<template>
<div class="design-grid-table">
<table>
<thead>
<tr>
<th v-for="(header, i) in tableHeaders" :key="i">{{ header }}</th>
</tr>
</thead>
<tbody>
<tr v-for="row in tableRows" :key="row">
<td v-for="col in tableCols" :key="col">
单元格 {{ row }}-{{ col }}
</td>
</tr>
</tbody>
</table>
</div>
</template>
<style scoped>
.design-grid-table {
padding: 8px;
background: #2d2d2d;
border-radius: 4px;
overflow-x: auto;
}
table {
width: 100%;
border-collapse: collapse;
font-size: 12px;
}
th, td {
padding: 6px 8px;
border: 1px solid #3c3c3c;
text-align: left;
color: #cccccc;
}
th {
background: #1e1e1e;
font-weight: 500;
}
td {
background: #252526;
}
</style>

View File

@@ -0,0 +1,9 @@
<el-col :span="24">
<div class="design-component design-grid-table" data-component="表格">
<el-table :data="tableData" border style="width: 100%">
<el-table-column prop="col1" label="列1" />
<el-table-column prop="col2" label="列2" />
<el-table-column prop="col3" label="列3" />
</el-table>
</div>
</el-col>

View File

@@ -1,7 +1,49 @@
{
"id": "RadioSelect",
"name": "单选器",
"icon": "⭕",
"description": "用于选择单个选项的表单组件",
"props": {
"options": ["选项1", "选项2", "选项3"]
"template": "template.html",
"defaultSpan": 12,
"metadata": {
"span": {
"label": "宽度",
"type": "number",
"min": 1,
"max": 24,
"target": "el-col",
"attr": ":span"
},
"label": {
"label": "标签",
"type": "text",
"target": "el-form-item",
"attr": "label"
},
"size": {
"label": "尺寸",
"type": "select",
"options": ["", "medium", "small", "mini"],
"target": "el-radio-group",
"attr": "size"
},
"disabled": {
"label": "禁用",
"type": "boolean",
"target": "el-radio-group",
"attr": "disabled"
},
"fill": {
"label": "填充色",
"type": "color",
"target": "el-radio-group",
"attr": "fill"
},
"textColor": {
"label": "文字颜色",
"type": "color",
"target": "el-radio-group",
"attr": "text-color"
}
}
}

View File

@@ -1,75 +0,0 @@
<script setup lang="ts">
import { ref } from 'vue'
const props = defineProps<{
options?: string[]
}>()
const selected = ref<string | null>(null)
</script>
<template>
<div class="design-radio-select">
<div
v-for="option in (options || [])"
:key="option"
class="radio-item"
@click="selected = option"
>
<span class="radio-circle" :class="{ active: selected === option }">
<span class="radio-dot" v-if="selected === option"></span>
</span>
<span class="radio-label">{{ option }}</span>
</div>
</div>
</template>
<style scoped>
.design-radio-select {
display: flex;
flex-direction: column;
gap: 6px;
padding: 8px;
background: #2d2d2d;
border-radius: 4px;
}
.radio-item {
display: flex;
align-items: center;
gap: 8px;
padding: 4px;
cursor: pointer;
border-radius: 4px;
}
.radio-item:hover {
background: #3c3c3c;
}
.radio-circle {
width: 16px;
height: 16px;
border: 2px solid #555;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
}
.radio-circle.active {
border-color: #007acc;
}
.radio-dot {
width: 8px;
height: 8px;
background: #007acc;
border-radius: 50%;
}
.radio-label {
color: #cccccc;
font-size: 13px;
}
</style>

View File

@@ -0,0 +1,11 @@
<el-col :span="12">
<div class="design-component design-radio-select" data-component="单选器">
<el-form-item label="单选选择">
<el-radio-group v-model="radioValue">
<el-radio label="选项1" value="1" />
<el-radio label="选项2" value="2" />
<el-radio label="选项3" value="3" />
</el-radio-group>
</el-form-item>
</div>
</el-col>

View File

@@ -1,9 +1,51 @@
{
"name": "文本输入框",
"id": "TextInput",
"name": "输入框",
"icon": "✏️",
"description": "用于输入文本的表单组件",
"props": {
"label": "标签名称",
"width": 200,
"maxLength": 100
"template": "template.html",
"defaultSpan": 12,
"metadata": {
"span": {
"label": "宽度",
"type": "number",
"min": 1,
"max": 24,
"target": "el-col",
"attr": ":span"
},
"label": {
"label": "标签",
"type": "text",
"target": "el-form-item",
"attr": "label"
},
"type": {
"label": "类型",
"type": "select",
"options": ["", "text", "textarea"],
"target": "el-input",
"attr": "type"
},
"placeholder": {
"label": "占位文本",
"type": "text",
"target": "el-input",
"attr": "placeholder"
},
"minlength": {
"label": "最小长度",
"type": "number",
"min": 0,
"target": "el-input",
"attr": "minlength"
},
"maxlength": {
"label": "最大长度",
"type": "number",
"min": 0,
"target": "el-input",
"attr": "maxlength"
}
}
}

View File

@@ -1,49 +0,0 @@
<script setup lang="ts">
defineProps<{
label?: string
width?: number
maxLength?: number
}>()
</script>
<template>
<div class="design-text-input" :style="{ width: width + 'px' }">
<label class="input-label">{{ label }}</label>
<input
type="text"
class="input-field"
:maxlength="maxLength"
placeholder="请输入..."
/>
</div>
</template>
<style scoped>
.design-text-input {
display: flex;
flex-direction: column;
gap: 4px;
padding: 8px;
background: #2d2d2d;
border-radius: 4px;
}
.input-label {
color: #cccccc;
font-size: 12px;
}
.input-field {
padding: 6px 8px;
background: #1e1e1e;
border: 1px solid #3c3c3c;
border-radius: 4px;
color: #d4d4d4;
font-size: 13px;
outline: none;
}
.input-field:focus {
border-color: #007acc;
}
</style>

View File

@@ -0,0 +1,7 @@
<el-col :span="12">
<div class="design-component design-text-input" data-component="输入框">
<el-form-item label="文本输入">
<el-input v-model="inputValue" placeholder="请输入内容"></el-input>
</el-form-item>
</div>
</el-col>

View File

@@ -1,17 +1,4 @@
{
"name": "数据表格",
"description": "展示属性和值的简单表格组件",
"props": {
"columns": ["属性", "值"],
"data": [
{ "property": "项目名称", "value": "draggable-panels" },
{ "property": "框架", "value": "Vue 3" },
{ "property": "语言", "value": "TypeScript" },
{ "property": "构建工具", "value": "Vite" },
{ "property": "状态管理", "value": "Pinia" },
{ "property": "版本", "value": "1.0.0" },
{ "property": "作者", "value": "Developer" },
{ "property": "许可证", "value": "MIT" }
]
}
"name": "数据",
"description": "展示和编辑设计组件的属性"
}

View File

@@ -1,125 +1,224 @@
<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { ref, watch } from 'vue'
import { useDesignStore } from '../../stores/designStore'
import { useVueFileStore } from '../../stores/vueFileStore'
import config from './index.json'
const TEMPLATE_SERVICE_URL = 'http://localhost:3001'
const designStore = useDesignStore()
const vueFileStore = useVueFileStore()
// 编辑状态
const editingCell = ref<{ key: string } | null>(null)
const editValue = ref('')
// 本地编辑值
const localValues = ref<Record<string, any>>({})
// 获取选中组件的属性列表
const propertyList = computed(() => {
const comp = designStore.selectedComponent
if (!comp) return []
return Object.entries(comp.props).map(([key, value]) => ({
key,
value: formatValue(value),
rawValue: value
}))
})
// 更新中状态
const updating = ref(false)
// 格式化显示
const formatValue = (value: any): string => {
if (Array.isArray(value)) {
return value.join(', ')
// 初始化本地
watch(() => designStore.selectedComponent, (comp) => {
if (comp) {
localValues.value = { ...comp.props }
// 提取 span 值
if (comp.props.span !== undefined) {
localValues.value.span = comp.props.span
}
} else {
localValues.value = {}
}
return String(value)
}
}, { immediate: true, deep: true })
// 开始编辑
const startEdit = (key: string, value: any) => {
editingCell.value = { key }
editValue.value = formatValue(value)
}
// 完成编辑
const finishEdit = () => {
if (editingCell.value && designStore.selectedId) {
const { key } = editingCell.value
// 尝试解析值
let newValue: any = editValue.value
// 更新属性
const updateProp = async (key: string, value: any) => {
if (!designStore.selectedComponent || !vueFileStore.selectedFilePath) return
updating.value = true
try {
const updates: Record<string, any> = {}
// 如果原始值是数组,尝试解析为数组
const comp = designStore.selectedComponent
if (comp && Array.isArray(comp.props[key])) {
newValue = editValue.value.split(',').map(s => s.trim())
} else if (!isNaN(Number(editValue.value)) && editValue.value !== '') {
newValue = Number(editValue.value)
// 根据元数据 schema 构建更新
const schema = designStore.selectedMetadataSchema
if (schema && schema[key]) {
const field = schema[key]
if (key === 'span') {
updates.span = value
} else {
updates[`${field.target}:${field.attr}`] = value
}
}
designStore.updateComponentProps(designStore.selectedId, key, newValue)
editingCell.value = null
const response = await fetch(`${TEMPLATE_SERVICE_URL}/api/update-props`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
pagePath: vueFileStore.selectedFilePath,
elementPath: designStore.selectedComponent.path,
updates
})
})
const result = await response.json()
if (result.success) {
console.log('[元数据] 更新成功:', key, value)
// 触发页面刷新
window.dispatchEvent(new CustomEvent('vue-template-updated', {
detail: { pagePath: vueFileStore.selectedFilePath }
}))
} else {
console.error('[元数据] 更新失败:', result.error)
}
} catch (error) {
console.error('[元数据] 请求失败:', error)
} finally {
updating.value = false
}
}
// 取消编辑
const cancelEdit = () => {
editingCell.value = null
// 输入变化处理
const handleInputChange = (key: string, event: Event) => {
const target = event.target as HTMLInputElement
let value: any = target.value
const schema = designStore.selectedMetadataSchema
if (schema && schema[key]) {
if (schema[key].type === 'number') {
value = parseInt(value) || 0
} else if (schema[key].type === 'boolean') {
value = target.checked
}
}
localValues.value[key] = value
updateProp(key, value)
}
// 检查是否正在编辑
const isEditing = (key: string) => {
return editingCell.value?.key === key
// 选择变化处理
const handleSelectChange = (key: string, event: Event) => {
const target = event.target as HTMLSelectElement
localValues.value[key] = target.value
updateProp(key, target.value)
}
// 布尔值变化处理
const handleBooleanChange = (key: string, event: Event) => {
const target = event.target as HTMLInputElement
localValues.value[key] = target.checked
updateProp(key, target.checked)
}
// 色彩变化处理
const handleColorChange = (key: string, event: Event) => {
const target = event.target as HTMLInputElement
localValues.value[`${designStore.selectedMetadataSchema?.[key]?.target}:${designStore.selectedMetadataSchema?.[key]?.attr}`] = target.value
updateProp(key, target.value)
}
</script>
<template>
<div class="data-table">
<div class="table-header">
<div class="metadata-editor">
<div class="editor-header">
<span class="title">{{ config.name }}</span>
<span class="hint" v-if="designStore.selectedComponent">
{{ designStore.selectedComponent.name }}
{{ designStore.selectedComponent.componentName }}
</span>
<span class="hint" v-else>请选择组件</span>
</div>
<div class="table-body">
<table class="table" v-if="propertyList.length > 0">
<thead>
<tr>
<th>属性</th>
<th></th>
</tr>
</thead>
<tbody>
<tr v-for="prop in propertyList" :key="prop.key">
<td class="prop-key">{{ prop.key }}</td>
<td @dblclick="startEdit(prop.key, prop.rawValue)">
<input
v-if="isEditing(prop.key)"
v-model="editValue"
class="edit-input"
@blur="finishEdit"
@keyup.enter="finishEdit"
@keyup.escape="cancelEdit"
autofocus
/>
<span v-else class="cell-value">{{ prop.value }}</span>
</td>
</tr>
</tbody>
</table>
<div class="editor-body">
<!-- 有选中组件且有元数据 -->
<div v-if="designStore.selectedComponent && designStore.selectedMetadataSchema" class="props-list">
<div
v-for="(field, key) in designStore.selectedMetadataSchema"
:key="key"
class="prop-item"
>
<label class="prop-label">{{ field.label }}</label>
<!-- 数字输入 -->
<input
v-if="field.type === 'number'"
type="number"
class="prop-input"
:min="field.min"
:max="field.max"
:value="localValues[key] ?? localValues.span"
@change="handleInputChange(key as string, $event)"
:disabled="updating"
/>
<!-- 文本输入 -->
<input
v-else-if="field.type === 'text'"
type="text"
class="prop-input"
:value="localValues[`${field.target}:${field.attr}`] || ''"
@change="handleInputChange(key as string, $event)"
:disabled="updating"
/>
<!-- 单选下拉 -->
<select
v-else-if="field.type === 'select'"
class="prop-select"
:value="localValues[`${field.target}:${field.attr}`] || ''"
@change="handleSelectChange(key as string, $event)"
:disabled="updating"
>
<option v-for="opt in field.options" :key="opt" :value="opt">
{{ opt || '默认' }}
</option>
</select>
<!-- 布尔开关 -->
<label v-else-if="field.type === 'boolean'" class="prop-checkbox">
<input
type="checkbox"
:checked="localValues[`${field.target}:${field.attr}`] === 'true' || localValues[`${field.target}:${field.attr}`] === true"
@change="handleBooleanChange(key as string, $event)"
:disabled="updating"
/>
<span class="checkbox-text">{{ localValues[`${field.target}:${field.attr}`] ? '是' : '否' }}</span>
</label>
<!-- 颜色选择器 -->
<div v-else-if="field.type === 'color'" class="color-picker-wrapper">
<input
type="color"
class="prop-color"
:value="localValues[`${field.target}:${field.attr}`] || '#409EFF'"
@input="handleColorChange(key as string, $event)"
:disabled="updating"
/>
<span class="color-value">{{ localValues[`${field.target}:${field.attr}`] || '#409EFF' }}</span>
</div>
<!-- 列配置暂不支持 -->
<span v-else-if="field.type === 'columns'" class="prop-hint">
(暂不支持编辑)
</span>
</div>
</div>
<!-- 空状态 -->
<div v-else class="empty-tip">
<div class="empty-icon">📋</div>
<div>暂无属性</div>
<div class="empty-hint">先在树形或设计中心选择一个组件</div>
<div>暂无元数据</div>
<div class="empty-hint">点击设计中心或结构树中的组件</div>
</div>
</div>
</div>
</template>
<style scoped>
.data-table {
.metadata-editor {
display: flex;
flex-direction: column;
height: 100%;
background: #1e1e1e;
}
.table-header {
.editor-header {
padding: 8px 12px;
background: #2d2d2d;
border-bottom: 1px solid #3c3c3c;
@@ -135,74 +234,94 @@ const isEditing = (key: string) => {
}
.hint {
color: #007acc;
color: #4fc3f7;
font-size: 11px;
}
.table-body {
.editor-body {
flex: 1;
padding: 12px;
overflow: auto;
}
.table {
width: 100%;
border-collapse: collapse;
font-size: 13px;
.props-list {
display: flex;
flex-direction: column;
gap: 12px;
}
.table th,
.table td {
padding: 10px 12px;
text-align: left;
border-bottom: 1px solid #3c3c3c;
.prop-item {
display: flex;
align-items: center;
gap: 12px;
}
.table th {
background: #2d2d2d;
color: #cccccc;
font-weight: 500;
}
.table td {
color: #d4d4d4;
cursor: pointer;
position: relative;
}
.table td.prop-key {
.prop-label {
min-width: 80px;
color: #9cdcfe;
font-family: monospace;
cursor: default;
font-size: 12px;
}
.table td:hover {
background: #2a2d2e;
}
.table tbody tr:hover {
background: #2a2d2e;
}
.cell-value {
display: block;
min-height: 20px;
}
.edit-input {
width: 100%;
padding: 4px 8px;
.prop-input,
.prop-select {
flex: 1;
padding: 6px 10px;
background: #3c3c3c;
border: 1px solid #007acc;
border-radius: 3px;
color: #ffffff;
font-size: 13px;
border: 1px solid #555;
border-radius: 4px;
color: #fff;
font-size: 12px;
outline: none;
}
.edit-input:focus {
.prop-input:focus,
.prop-select:focus {
border-color: #007acc;
box-shadow: 0 0 0 2px rgba(0, 122, 204, 0.3);
}
.prop-input:disabled,
.prop-select:disabled {
opacity: 0.6;
}
.prop-checkbox {
display: flex;
align-items: center;
gap: 8px;
cursor: pointer;
}
.checkbox-text {
color: #ccc;
font-size: 12px;
}
.prop-color {
width: 40px;
height: 30px;
padding: 2px;
background: #3c3c3c;
border: 1px solid #555;
border-radius: 4px;
cursor: pointer;
}
.color-picker-wrapper {
display: flex;
align-items: center;
gap: 10px;
}
.color-value {
color: #ccc;
font-size: 12px;
font-family: monospace;
}
.prop-hint {
color: #666;
font-size: 11px;
font-style: italic;
}
.empty-tip {

View File

@@ -3,6 +3,7 @@ import { ref, onMounted, onUnmounted, watch, nextTick, computed } from 'vue'
import { useInteractionStore, useDragStore, generateElementPath } from '../../plugins'
import type { ElementType, InteractionTarget } from '../../plugins'
import { useVueFileStore } from '../../stores/vueFileStore'
import { useDesignStore } from '../../stores/designStore'
import DropZone from './DropZone.vue'
import DragPreview from './DragPreview.vue'
@@ -13,8 +14,12 @@ const props = defineProps<{
const interactionStore = useInteractionStore()
const dragStore = useDragStore()
const vueFileStore = useVueFileStore()
const designStore = useDesignStore()
const containerRef = ref<HTMLElement | null>(null)
// 右键菜单状态
const contextMenu = ref<{ x: number, y: number, path: string, type: ElementType } | null>(null)
// 存储所有绑定的事件清理函数
const cleanupFunctions: (() => void)[] = []
@@ -92,6 +97,21 @@ const bindElementEvents = (element: HTMLElement, type: ElementType, path: string
el.classList.remove('fauto-selected')
})
element.classList.add('fauto-selected')
// 检查是否是叶子节点(设计组件)
if (type === 'ec') {
const componentDiv = element.querySelector('[data-component]')
if (componentDiv && vueFileStore.selectedFilePath) {
const componentName = componentDiv.getAttribute('data-component')
if (componentName) {
designStore.selectComponent(path, componentName, vueFileStore.selectedFilePath)
// 触发自定义事件,通知结构树同步选中
window.dispatchEvent(new CustomEvent('design-component-selected', {
detail: { path, componentName }
}))
}
}
}
}
// 鼠标按下(画布内元素拖拽)
@@ -105,11 +125,19 @@ const bindElementEvents = (element: HTMLElement, type: ElementType, path: string
dragStore.startDragFromCanvas(path, type, element)
}
// 右键菜单
const handleContextMenu = (e: MouseEvent) => {
e.preventDefault()
e.stopPropagation()
contextMenu.value = { x: e.clientX, y: e.clientY, path, type }
}
// 绑定事件
element.addEventListener('mouseenter', handleMouseEnter)
element.addEventListener('mouseleave', handleMouseLeave)
element.addEventListener('click', handleClick)
element.addEventListener('mousedown', handleMouseDown)
element.addEventListener('contextmenu', handleContextMenu)
console.log(`[注入] ${type} 路径: ${path}`)
@@ -119,11 +147,60 @@ const bindElementEvents = (element: HTMLElement, type: ElementType, path: string
element.removeEventListener('mouseleave', handleMouseLeave)
element.removeEventListener('click', handleClick)
element.removeEventListener('mousedown', handleMouseDown)
element.removeEventListener('contextmenu', handleContextMenu)
element.classList.remove('fauto-interactive', 'fauto-hover', 'fauto-selected')
element.removeAttribute('data-fauto-bindend')
}
}
// 关闭右键菜单
const closeContextMenu = () => {
contextMenu.value = null
}
// 删除元素
const deleteElement = async () => {
if (!contextMenu.value || !vueFileStore.selectedFilePath) return
const { path } = contextMenu.value
if (!confirm('确定要删除该元素吗?')) {
closeContextMenu()
return
}
try {
const response = await fetch('http://localhost:3001/api/delete-element', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
pagePath: vueFileStore.selectedFilePath,
elementPath: path
})
})
const result = await response.json()
if (result.success) {
console.log('[设计中心] 删除成功:', path)
window.dispatchEvent(new CustomEvent('vue-template-updated', {
detail: { pagePath: vueFileStore.selectedFilePath }
}))
// 如果删除的是选中的组件,清除选中
if (designStore.selectedComponent?.path === path) {
designStore.clearSelection()
}
} else {
alert('删除失败: ' + result.error)
}
} catch (error) {
console.error('[设计中心] 删除失败:', error)
}
closeContextMenu()
}
/**
* 扫描并注入事件到所有el-row和el-col元素
*/
@@ -275,6 +352,8 @@ onMounted(() => {
document.addEventListener('mousemove', handleGlobalMouseMove)
// 添加全局鼠标松开事件
document.addEventListener('mouseup', handleGlobalMouseUp)
// 点击其他地方关闭右键菜单
document.addEventListener('click', closeContextMenu)
})
// 组件卸载时清理事件
@@ -291,6 +370,7 @@ onUnmounted(() => {
document.removeEventListener('keydown', handleKeyDown)
document.removeEventListener('mousemove', handleGlobalMouseMove)
document.removeEventListener('mouseup', handleGlobalMouseUp)
document.removeEventListener('click', closeContextMenu)
})
// 监听组件变化,重新注入事件
@@ -324,6 +404,18 @@ watch(() => interactionStore.hoverTarget, (target) => {
<!-- 拖拽预览跟随鼠标 -->
<DragPreview />
<!-- 右键菜单 -->
<div
v-if="contextMenu"
class="context-menu"
:style="{ left: contextMenu.x + 'px', top: contextMenu.y + 'px' }"
>
<div class="menu-item delete" @click="deleteElement">
<span class="menu-icon">🗑</span>
<span>删除</span>
</div>
</div>
<!-- 拖拽时的层级选择提示 -->
<div v-if="dragStore.isDragging && dragStore.hierarchyNodes.length > 1" class="hierarchy-hint">
<div class="hint-title"> 用上下键切换层级</div>
@@ -444,4 +536,39 @@ watch(() => interactionStore.hoverTarget, (target) => {
.hint-path {
font-family: monospace;
}
/* 右键菜单 */
.context-menu {
position: fixed;
background: #2d2d2d;
border: 1px solid #3c3c3c;
border-radius: 6px;
box-shadow: 0 4px 12px rgba(0,0,0,0.4);
z-index: 2000;
min-width: 120px;
padding: 4px 0;
}
.menu-item {
padding: 8px 16px;
cursor: pointer;
display: flex;
align-items: center;
gap: 8px;
color: #ccc;
font-size: 13px;
transition: background 0.15s;
}
.menu-item:hover {
background: #094771;
}
.menu-item.delete:hover {
background: #c23a3a;
}
.menu-icon {
font-size: 14px;
}
</style>

View File

@@ -30,10 +30,6 @@ onUnmounted(() => {
}
})
const handleAddComponent = (componentId: string) => {
designStore.addComponent(componentId)
}
// 鼠标悬停设计组件
const handleMouseEnter = (componentId: string, componentName: string) => {
const target: InteractionTarget = {
@@ -60,15 +56,13 @@ const handleClick = (componentId: string, componentName: string) => {
componentId: componentName
}
interactionStore.onClick(target)
// 添加组件
designStore.addComponent(componentId)
}
// 鼠标按下 - 开始检测拖拽
// 鼠标按下 - 开始拖拽
const handleMouseDown = (e: MouseEvent, componentId: string, componentName: string) => {
e.preventDefault()
// 立即开始拖拽(不需要长按)
// 立即开始拖拽
draggingId.value = componentId
dragStore.startDragFromComponentList(componentId, componentName)
}
@@ -100,7 +94,7 @@ const handleGlobalMouseUp = () => {
@mouseleave="handleMouseLeave"
@mousedown="handleMouseDown($event, meta.id, meta.name)"
>
<div class="component-icon">📦</div>
<div class="component-icon">{{ meta.icon }}</div>
<div class="component-info">
<div class="component-name">{{ meta.name }}</div>
<div class="component-desc">{{ meta.description }}</div>

View File

@@ -1,36 +1,4 @@
{
"name": "树形展示器",
"description": "用于展示树形结构数据的组件",
"props": {
"treeData": [
{
"id": "1",
"label": "项目根目录",
"expanded": true,
"children": [
{
"id": "1-1",
"label": "src",
"expanded": true,
"children": [
{ "id": "1-1-1", "label": "components" },
{ "id": "1-1-2", "label": "stores" },
{ "id": "1-1-3", "label": "types" },
{ "id": "1-1-4", "label": "App.vue" },
{ "id": "1-1-5", "label": "main.ts" }
]
},
{
"id": "1-2",
"label": "public",
"children": [
{ "id": "1-2-1", "label": "favicon.ico" }
]
},
{ "id": "1-3", "label": "package.json" },
{ "id": "1-4", "label": "vite.config.ts" }
]
}
]
}
"name": "结构",
"description": "展示当前页面的el-row/el-col布局结构"
}

View File

@@ -1,77 +1,394 @@
<script setup lang="ts">
import { ref, watch } from 'vue'
import draggable from 'vuedraggable'
import { ref, watch, onMounted, onUnmounted } from 'vue'
import { useVueFileStore } from '../../stores/vueFileStore'
import { useDesignStore } from '../../stores/designStore'
import config from './index.json'
const TEMPLATE_SERVICE_URL = 'http://localhost:3001'
const vueFileStore = useVueFileStore()
const designStore = useDesignStore()
// 创建可响应的本地副本用于拖拽
const localComponents = ref([...designStore.components])
// 元素树节点类型
interface ElementNode {
type: 'row' | 'col'
path: string
label: string
componentName?: string | null
children?: ElementNode[]
}
// 监听 designStore 组件变化,同步到本地副本
watch(
() => designStore.components,
(newVal) => {
localComponents.value = [...newVal]
},
{ deep: true, immediate: true }
)
// 元素树数据
const elementTree = ref<ElementNode[]>([])
const loading = ref(false)
// 拖拽结束处理 - 同步顺序到 designStore
const onDragEnd = () => {
// 重新排序 designStore 中的组件
designStore.reorderComponents([...localComponents.value])
// 拖拽状态
const draggingNode = ref<ElementNode | null>(null)
const dropTarget = ref<{ node: ElementNode, position: 'before' | 'after' | 'inside' } | null>(null)
// 右键菜单状态
const contextMenu = ref<{ x: number, y: number, node: ElementNode } | null>(null)
// 选中的节点
const selectedPath = ref<string | null>(null)
// 获取页面元素结构
const fetchElementTree = async () => {
if (!vueFileStore.selectedFilePath) {
elementTree.value = []
return
}
loading.value = true
try {
const response = await fetch(
`${TEMPLATE_SERVICE_URL}/api/element-tree?pagePath=${encodeURIComponent(vueFileStore.selectedFilePath)}`
)
const result = await response.json()
if (result.success) {
elementTree.value = result.tree || []
} else {
elementTree.value = []
}
} catch (error) {
elementTree.value = []
} finally {
loading.value = false
}
}
// 获取节点显示文本
const getNodeText = (node: ElementNode): string => {
if (node.type === 'row') return node.path
if (node.componentName) return `${node.path}-${node.componentName}`
return node.path
}
// 判断是否为叶子节点
const isLeafNode = (node: ElementNode): boolean => {
return node.type === 'col' && !!node.componentName && (!node.children || node.children.length === 0)
}
// 计算允许的放置位置
const getAllowedPosition = (source: ElementNode, target: ElementNode): 'before' | 'after' | 'inside' | null => {
if (source.path === target.path) return null
if (target.path.startsWith(source.path)) return null
if (source.type === 'col' && target.type === 'col') return 'after'
if (source.type === 'row' && target.type === 'row') return 'after'
if (source.type === 'col' && target.type === 'row') return 'inside'
if (source.type === 'row' && target.type === 'col' && !isLeafNode(target)) return 'inside'
return null
}
// 点击节点 - 选中组件
const handleNodeClick = (nodeId: string) => {
designStore.selectComponent(nodeId)
const handleNodeClick = (node: ElementNode) => {
selectedPath.value = node.path
// 如果是叶子节点,选中组件显示元数据
if (isLeafNode(node) && node.componentName && vueFileStore.selectedFilePath) {
designStore.selectComponent(node.path, node.componentName, vueFileStore.selectedFilePath)
}
// 高亮设计中心对应元素
highlightDesignCenterElement(node.path)
}
// 获取组件类型图标
const getComponentIcon = (componentId: string) => {
const icons: Record<string, string> = {
TextInput: '✏️',
RadioSelect: '◉',
GridTable: '☰'
// 高亮设计中心的对应元素
const highlightDesignCenterElement = (path: string) => {
// 移除其他选中
document.querySelectorAll('.fauto-selected').forEach(el => {
el.classList.remove('fauto-selected')
})
// 找到对应元素并选中
const element = document.querySelector(`[data-path="${path}"]`)
if (element) {
element.classList.add('fauto-selected')
// 滚动到可见区域
element.scrollIntoView({ behavior: 'smooth', block: 'center' })
}
return icons[componentId] || '⭕'
}
// 监听设计中心的选中事件,同步选中结构树
const handleDesignComponentSelected = (e: CustomEvent) => {
const { path } = e.detail
if (path) {
selectedPath.value = path
}
}
// 右键菜单
const handleContextMenu = (e: MouseEvent, node: ElementNode) => {
e.preventDefault()
e.stopPropagation()
contextMenu.value = { x: e.clientX, y: e.clientY, node }
}
// 关闭右键菜单
const closeContextMenu = () => {
contextMenu.value = null
}
// 删除节点
const deleteNode = async (node: ElementNode) => {
if (!vueFileStore.selectedFilePath) return
if (!confirm(`确定要删除 ${getNodeText(node)} 吗?`)) return
try {
const response = await fetch(`${TEMPLATE_SERVICE_URL}/api/delete-element`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
pagePath: vueFileStore.selectedFilePath,
elementPath: node.path
})
})
const result = await response.json()
if (result.success) {
console.log('[结构] 删除成功:', node.path)
window.dispatchEvent(new CustomEvent('vue-template-updated', {
detail: { pagePath: vueFileStore.selectedFilePath }
}))
// 如果删除的是选中的组件,清除选中
if (designStore.selectedComponent?.path === node.path) {
designStore.clearSelection()
}
} else {
alert('删除失败: ' + result.error)
}
} catch (error) {
console.error('[结构] 删除失败:', error)
}
closeContextMenu()
}
// 键盘事件处理
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === 'Delete' && selectedPath.value) {
const node = findNodeByPath(elementTree.value, selectedPath.value)
if (node) {
deleteNode(node)
}
}
if (e.key === 'Escape') {
closeContextMenu()
}
}
// 查找节点
const findNodeByPath = (nodes: ElementNode[], path: string): ElementNode | null => {
for (const node of nodes) {
if (node.path === path) return node
if (node.children) {
const found = findNodeByPath(node.children, path)
if (found) return found
}
}
return null
}
// 拖拽事件
const handleDragStart = (e: DragEvent, node: ElementNode) => {
draggingNode.value = node
if (e.dataTransfer) {
e.dataTransfer.effectAllowed = 'move'
e.dataTransfer.setData('text/plain', node.path)
}
}
const handleDragOver = (e: DragEvent, node: ElementNode) => {
if (!draggingNode.value) return
const position = getAllowedPosition(draggingNode.value, node)
if (position) {
e.preventDefault()
dropTarget.value = { node, position }
} else {
dropTarget.value = null
}
}
const handleDragLeave = () => {
dropTarget.value = null
}
const handleDrop = async (e: DragEvent, node: ElementNode) => {
e.preventDefault()
if (!draggingNode.value || !vueFileStore.selectedFilePath) {
resetDragState()
return
}
const position = getAllowedPosition(draggingNode.value, node)
if (!position) {
resetDragState()
return
}
let direction: string
if (position === 'inside') {
direction = 'inside'
} else if (position === 'after') {
direction = node.type === 'row' ? 'bottom' : 'right'
} else {
direction = node.type === 'row' ? 'top' : 'left'
}
try {
const response = await fetch(`${TEMPLATE_SERVICE_URL}/api/move-element`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
pagePath: vueFileStore.selectedFilePath,
source: {
type: 'canvas-element',
path: draggingNode.value.path,
elementType: draggingNode.value.type === 'row' ? 'er' : 'ec'
},
targetPath: node.path,
targetType: node.type === 'row' ? 'er' : 'ec',
direction
})
})
const result = await response.json()
if (result.success) {
window.dispatchEvent(new CustomEvent('vue-template-updated', {
detail: { pagePath: vueFileStore.selectedFilePath }
}))
}
} catch (error) {
console.error('[结构] 移动失败:', error)
}
resetDragState()
}
const handleDragEnd = () => {
resetDragState()
}
const resetDragState = () => {
draggingNode.value = null
dropTarget.value = null
}
// 递归渲染树
const flattenTree = (nodes: ElementNode[], depth = 0): Array<{ node: ElementNode, depth: number }> => {
const result: Array<{ node: ElementNode, depth: number }> = []
for (const node of nodes) {
result.push({ node, depth })
if (node.children && node.children.length > 0) {
result.push(...flattenTree(node.children, depth + 1))
}
}
return result
}
// 获取节点样式类
const getNodeClass = (node: ElementNode) => {
const classes: string[] = []
if (node.type === 'row') classes.push('is-row')
if (node.type === 'col') classes.push('is-col')
if (draggingNode.value?.path === node.path) classes.push('is-dragging')
if (selectedPath.value === node.path) classes.push('is-selected')
if (dropTarget.value?.node.path === node.path) {
classes.push('is-drop-target')
classes.push(`drop-${dropTarget.value.position}`)
}
return classes
}
// 监听
watch(() => vueFileStore.selectedFilePath, () => {
fetchElementTree()
}, { immediate: true })
onMounted(() => {
window.addEventListener('vue-template-updated', () => {
setTimeout(fetchElementTree, 300)
})
// 监听设计中心的选中事件
window.addEventListener('design-component-selected', handleDesignComponentSelected as EventListener)
document.addEventListener('keydown', handleKeyDown)
document.addEventListener('click', closeContextMenu)
// 阻止组件内的浏览器默认右键菜单
document.addEventListener('contextmenu', handleGlobalContextMenu)
})
// 全局右键菜单处理,阻止浏览器默认菜单
const handleGlobalContextMenu = (e: MouseEvent) => {
// 检查是否在树节点上点击
const target = e.target as HTMLElement
if (target.closest('.tree-node')) {
e.preventDefault()
}
}
onUnmounted(() => {
document.removeEventListener('keydown', handleKeyDown)
document.removeEventListener('click', closeContextMenu)
document.removeEventListener('contextmenu', handleGlobalContextMenu)
window.removeEventListener('design-component-selected', handleDesignComponentSelected as EventListener)
})
</script>
<template>
<div class="tree-viewer">
<div class="viewer-header">
<span class="title">{{ config.name }}</span>
<span class="hint">设计组件列表</span>
</div>
<div class="viewer-body">
<div class="tree-container">
<draggable
:list="localComponents"
item-key="id"
:animation="150"
ghost-class="node-ghost"
@end="onDragEnd"
<div v-if="loading" class="loading-tip">加载中...</div>
<div v-else-if="elementTree.length === 0" class="empty-tip">
{{ vueFileStore.selectedFilePath ? '暂无布局元素' : '请先选择页面' }}
</div>
<div v-else class="tree-container">
<div
v-for="item in flattenTree(elementTree)"
:key="item.node.path"
class="tree-node"
:class="getNodeClass(item.node)"
:style="{ paddingLeft: (item.depth * 16 + 8) + 'px' }"
draggable="true"
@click="handleNodeClick(item.node)"
@contextmenu="handleContextMenu($event, item.node)"
@dragstart="handleDragStart($event, item.node)"
@dragover="handleDragOver($event, item.node)"
@dragleave="handleDragLeave"
@drop="handleDrop($event, item.node)"
@dragend="handleDragEnd"
>
<template #item="{ element: node }">
<div
class="tree-node"
:class="{ selected: designStore.selectedId === node.id }"
@click="handleNodeClick(node.id)"
>
<span class="node-icon">{{ getComponentIcon(node.componentId) }}</span>
<span class="node-label">{{ node.name }}</span>
</div>
</template>
</draggable>
<div v-if="localComponents.length === 0" class="empty-tip">
暂无设计组件
<span class="node-text">{{ getNodeText(item.node) }}</span>
<span v-if="dropTarget?.node.path === item.node.path" class="drop-hint">
{{ dropTarget.position === 'inside' ? '放入' : '后面' }}
</span>
<span class="delete-icon" @click.stop="deleteNode(item.node)" title="删除">🗑</span>
</div>
</div>
</div>
<!-- 右键菜单 -->
<div
v-if="contextMenu"
class="context-menu"
:style="{ left: contextMenu.x + 'px', top: contextMenu.y + 'px' }"
>
<div class="menu-item" @click="deleteNode(contextMenu.node)">
<span class="menu-icon">🗑</span>
<span>删除</span>
</div>
</div>
</div>
</template>
@@ -81,15 +398,13 @@ const getComponentIcon = (componentId: string) => {
flex-direction: column;
height: 100%;
background: #1e1e1e;
position: relative;
}
.viewer-header {
padding: 8px 12px;
background: #2d2d2d;
border-bottom: 1px solid #3c3c3c;
display: flex;
align-items: center;
justify-content: space-between;
}
.title {
@@ -98,11 +413,6 @@ const getComponentIcon = (componentId: string) => {
font-weight: 500;
}
.hint {
color: #666666;
font-size: 11px;
}
.viewer-body {
flex: 1;
padding: 8px;
@@ -110,43 +420,87 @@ const getComponentIcon = (componentId: string) => {
}
.tree-container {
font-size: 13px;
font-size: 12px;
font-family: 'Consolas', 'Monaco', monospace;
}
.tree-node {
padding: 4px 8px;
cursor: grab;
border-radius: 3px;
color: #888;
user-select: none;
margin-bottom: 1px;
transition: all 0.15s;
display: flex;
align-items: center;
padding: 8px 12px;
cursor: grab;
border-radius: 4px;
color: #cccccc;
user-select: none;
margin-bottom: 2px;
transition: all 0.15s;
}
.tree-node:active {
cursor: grabbing;
gap: 8px;
}
.tree-node:hover {
background: #2a2d2e;
}
.tree-node.selected {
.tree-node:hover .delete-icon {
opacity: 1;
}
.tree-node:active {
cursor: grabbing;
}
.tree-node.is-row {
color: #4fc3f7;
}
.tree-node.is-col {
color: #c586c0;
}
.tree-node.is-dragging {
opacity: 0.5;
}
.tree-node.is-selected {
background: #094771;
}
.node-icon {
width: 20px;
margin-right: 8px;
text-align: center;
.tree-node.is-drop-target {
background: #094771;
}
.node-label {
.tree-node.drop-inside {
border: 1px dashed #4fc3f7;
}
.tree-node.drop-after {
border-bottom: 2px solid #4fc3f7;
}
.node-text {
flex: 1;
}
.drop-hint {
font-size: 10px;
color: #4fc3f7;
background: rgba(79, 195, 247, 0.2);
padding: 1px 4px;
border-radius: 2px;
}
.delete-icon {
opacity: 0;
cursor: pointer;
font-size: 12px;
transition: opacity 0.15s;
}
.delete-icon:hover {
transform: scale(1.1);
}
.loading-tip,
.empty-tip {
color: #666666;
text-align: center;
@@ -154,10 +508,32 @@ const getComponentIcon = (componentId: string) => {
font-size: 12px;
}
/* 拖拽样式 */
.node-ghost {
opacity: 0.4;
background: #094771;
/* 右键菜单 */
.context-menu {
position: fixed;
background: #2d2d2d;
border: 1px solid #3c3c3c;
border-radius: 4px;
box-shadow: 0 4px 12px rgba(0,0,0,0.3);
z-index: 1000;
min-width: 120px;
}
.menu-item {
padding: 8px 12px;
cursor: pointer;
display: flex;
align-items: center;
gap: 8px;
color: #ccc;
font-size: 12px;
}
.menu-item:hover {
background: #094771;
}
.menu-icon {
font-size: 14px;
}
</style>

View File

@@ -100,9 +100,12 @@ export const useDragStore = defineStore('drag', () => {
/**
* 开始拖拽(从设计组件列表)
* 设计组件拖动直接进入目标选择阶段
*/
const startDragFromComponentList = (componentId: string, componentName: string) => {
isDragging.value = true
dragPhase.value = 'target' // 设计组件直接进入目标选择阶段
confirmedSource.value = null
dragSource.value = {
type: 'design-component',
componentId,
@@ -369,8 +372,14 @@ export const useDragStore = defineStore('drag', () => {
console.log('[DragStore] 确认拖放:', record)
// 如果提供了页面路径发送API请求到后端
if (pagePath && record.source.type === 'canvas-element') {
await sendMoveRequest(pagePath, record)
if (pagePath) {
if (record.source.type === 'canvas-element') {
// 画布内元素移动
await sendMoveRequest(pagePath, record)
} else if (record.source.type === 'design-component') {
// 设计组件插入
await sendInsertRequest(pagePath, record)
}
}
return record
@@ -414,6 +423,43 @@ export const useDragStore = defineStore('drag', () => {
}
}
/**
* 发送设计组件插入请求到后端服务
*/
const sendInsertRequest = async (pagePath: string, record: DropRecord) => {
try {
console.log('[DragStore] 发送插入请求:', { pagePath, record })
const response = await fetch(`${TEMPLATE_SERVICE_URL}/api/insert-component`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
pagePath,
componentId: record.source.componentId,
targetPath: record.targetPath,
direction: record.direction
})
})
const result = await response.json()
if (result.success) {
console.log('[DragStore] 插入成功:', result.message)
// 触发页面刷新事件
window.dispatchEvent(new CustomEvent('vue-template-updated', { detail: { pagePath } }))
} else {
console.error('[DragStore] 插入失败:', result.error)
}
return result
} catch (error) {
console.error('[DragStore] API请求失败:', error)
return { success: false, error: (error as Error).message }
}
}
/**
* 取消拖拽
*/

View File

@@ -1,11 +1,35 @@
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { ref, computed } from 'vue'
const TEMPLATE_SERVICE_URL = 'http://localhost:3001'
// 元数据字段定义
export interface MetadataField {
label: string
type: 'text' | 'number' | 'select' | 'boolean' | 'color' | 'columns'
min?: number
max?: number
options?: string[]
target: string
attr: string
}
// 设计组件定义
export interface DesignComponentMeta {
id: string
name: string
icon: string
description: string
template: string
defaultSpan: number
metadata?: Record<string, MetadataField>
}
// 选中的组件信息
export interface SelectedComponent {
path: string
componentId: string
componentName: string
props: Record<string, any>
}
@@ -13,28 +37,39 @@ export const useDesignStore = defineStore('design', () => {
// 设计组件元数据缓存
const componentMetas = ref<DesignComponentMeta[]>([])
// 当前选中的组件
const selectedComponent = ref<SelectedComponent | null>(null)
// 自动扫描所有设计组件的 .json 配置文件
const designComponentMetaModules = import.meta.glob('../designComponents/*/index.json', { eager: true })
// 自动扫描所有设计组件的模板文件
const designComponentTemplateModules = import.meta.glob('../designComponents/*/template.html', { eager: true, query: '?raw', import: 'default' })
// 加载设计组件元数据(从本地文件自动扫描)
// 加载设计组件元数据
const loadComponentMetas = async () => {
try {
const metas: DesignComponentMeta[] = []
for (const path in designComponentMetaModules) {
// 从路径中提取组件 ID例如 '../designComponents/TextInput/index.json' => 'TextInput'
const match = path.match(/\/designComponents\/(.+)\/index\.json$/)
if (!match) continue
const id = match[1]
const componentId = match[1]
const mod = designComponentMetaModules[path] as any
const config = mod.default || mod
const templatePath = `../designComponents/${componentId}/template.html`
const templateContent = designComponentTemplateModules[templatePath] as string || ''
metas.push({
id,
id: config.id || componentId,
name: config.name,
icon: config.icon || '📦',
description: config.description,
props: config.props || {}
template: templateContent,
defaultSpan: config.defaultSpan || 12,
metadata: config.metadata
})
}
@@ -49,10 +84,68 @@ export const useDesignStore = defineStore('design', () => {
const getComponentMeta = (componentId: string) => {
return componentMetas.value.find(m => m.id === componentId)
}
// 根据名称获取组件元数据
const getComponentMetaByName = (name: string) => {
return componentMetas.value.find(m => m.name === name)
}
// 获取组件模板
const getComponentTemplate = (componentId: string): string | null => {
const meta = getComponentMeta(componentId)
return meta?.template || null
}
// 选中组件
const selectComponent = async (path: string, componentName: string, pagePath: string) => {
try {
// 获取组件属性
const response = await fetch(
`${TEMPLATE_SERVICE_URL}/api/component-props?pagePath=${encodeURIComponent(pagePath)}&elementPath=${encodeURIComponent(path)}`
)
const result = await response.json()
if (result.success) {
selectedComponent.value = {
path,
componentId: result.componentId || componentName,
componentName,
props: result.props || {}
}
console.log('[设计Store] 选中组件:', selectedComponent.value)
}
} catch (error) {
console.error('[设计Store] 获取组件属性失败:', error)
}
}
// 清除选中
const clearSelection = () => {
selectedComponent.value = null
}
// 获取当前选中组件的元数据schema
const selectedMetadataSchema = computed(() => {
if (!selectedComponent.value) return null
const meta = getComponentMetaByName(selectedComponent.value.componentName)
return meta?.metadata || null
})
// 初始化
const init = async () => {
await loadComponentMetas()
}
return {
componentMetas,
selectedComponent,
selectedMetadataSchema,
init,
loadComponentMetas,
getComponentMeta
getComponentMeta,
getComponentMetaByName,
getComponentTemplate,
selectComponent,
clearSelection
}
})

View File

@@ -1,27 +1,73 @@
<template>
<el-row class="page-container" :gutter="20">
<el-col :span="12">
<div class="design-component">左侧内容区域</div>
</el-col>
<el-row class="page-container" :gutter="20">
<el-col :span="12">
<div class="design-component design-text-input">
<el-form-item label="文本输入">
<el-input v-model="inputValue" placeholder="请输入内容"></el-input>
</el-form-item>
</div>
</el-col>
<el-col :span="12">
<el-row :gutter="10">
<el-col :span="24">
<div class="design-component">右侧标题</div>
</el-col>
</el-row>
<el-col :span="12">
<div class="design-component">右侧列2</div>
</el-col>
</el-row>
<el-row :gutter="10">
<el-row :gutter="10">
<el-col :span="12">
<div class="design-component">右侧列2</div>
</el-col>
<el-col :span="12">
<div class="design-component design-radio-select">
<el-form-item label="单选选择">
<el-radio-group v-model="radioValue">
<el-radio label="选项1" value="1" />
<el-radio label="选项2" value="2" />
<el-radio label="选项3" value="3" />
</el-radio-group>
</el-form-item>
</div>
</el-col>
<el-col :span="12">
<div class="design-component">左侧内容区域</div>
</el-col>
</el-row>
</el-col>
<el-col :span="12">
<div class="design-component">右侧列1</div>
</el-col>
</el-row>
<div class="design-component design-radio-select" data-component="单选器">
<el-form-item label="单选选择">
<el-radio-group text-color="#da0707" fill="#703e67" >
<el-radio label="选项1" value="1" />
<el-radio label="选项2" value="2" />
<el-radio label="选项3" value="3" />
</el-radio-group>
</el-form-item>
</div>
</el-col>
<el-col :span="16">
<div class="design-component design-grid-table" data-component="表格">
<el-table border="false" stripe="false" size="mini" :data="tableData" style="width: 100%">
<el-table-column prop="col1" label="列1" />
<el-table-column prop="col2" label="列2" />
<el-table-column prop="col3" label="列3" />
</el-table>
</div>
</el-col>
<el-col :span="12">
<div class="design-component design-text-input" data-component="输入框">
<el-form-item label="文本输入">
<el-input v-model="inputValue" placeholder="请输入内容111"></el-input>
</el-form-item>
</div>
</el-col>
</el-row>
</template>
<script setup lang="ts">