基础使用示例

这是一个完整的基础使用示例,展示了如何使用 auto-exhibition-template-sdk 从配置到组件取值的完整流程。

示例项目结构

configJson 文件可以放在项目任意位置,只要 vite.config 能导入即可。下面只是一个示例结构:

src/
├── components/
│   └── HeroSection.vue    // 使用 SDK 的组件
├── App.vue
├── main.ts
└── config.ts              // 模板配置示例位置
vite.config.ts

第一步:定义配置

创建 configJson 文件,文件名和目录可以按项目习惯调整:

// config.ts
import { defineTemplateConfig } from 'auto-exhibition-template-sdk/config'

const configJson = defineTemplateConfig({
  meta: {
    name: '示例模板',
    code: 'demo-template',
    version: '1.0.0'
  },
  dataSchema: {
    fields: [
      {
        key: 'title',
        type: 'string',
        label: '主标题',
        value: '欢迎使用 auto-exhibition-template-sdk'
      },
      {
        key: 'subtitle',
        type: 'string',
        label: '副标题',
        value: '面向模板项目的前端 SDK'
      }
    ]
  },
  functions: {
    showDetail: {
      label: '显示详情',
      description: '接收展项 ID 并切换到详情状态',
      direction: 'inout',
      params: [
        { name: 'id', type: 'string', required: true }
      ]
    }
  }
})

export default configJson

第二步:配置 Vite 插件

vite.config.ts 中启用插件:

// vite.config.ts
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import configJson from './src/config'
import { templateSdkPlugin } from 'auto-exhibition-template-sdk/vite'

export default defineConfig({
  plugins: [
    templateSdkPlugin({ configJson }),
    vue()
  ]
})

第三步:安装运行时

main.ts 中安装 TemplateSdk:

// main.ts
import { createApp } from 'vue'
import App from './App.vue'
import TemplateSdk from 'auto-exhibition-template-sdk'

const app = createApp(App)
app.use(TemplateSdk)
app.mount('#app')

第四步:在组件中取值

创建 src/components/HeroSection.vue

<!-- src/components/HeroSection.vue -->
<script setup>
import { useTemplateValue } from 'auto-exhibition-template-sdk'

// 读取标题字段,提供空字符串作为兜底值
const title = useTemplateValue('title', '默认标题')

// 读取副标题字段
const subtitle = useTemplateValue('subtitle', '')
</script>

<template>
  <section class="hero">
    <h1>{{ title }}</h1>
    <p class="subtitle">{{ subtitle }}</p>
  </section>
</template>

<style scoped>
.hero {
  text-align: center;
  padding: 48px 0;
}

h1 {
  font-size: 48px;
  margin-bottom: 16px;
}

.subtitle {
  font-size: 18px;
  color: #606266;
}
</style>

第五步:注册可联动函数

声明在 configJson.functions 中的函数需要在运行时注册 handler,后台和网关才能触发真实动作。

<!-- src/components/HeroSection.vue -->
<script setup>
import { registerTemplateFunction } from 'auto-exhibition-template-sdk'

registerTemplateFunction('showDetail', async (args) => {
  console.log('show detail', args.id)
  return { ok: true }
})
</script>

效果预览

运行 pnpm dev 后,你将看到:

欢迎使用 auto-exhibition-template-sdk

面向模板项目的前端 SDK

总结

完整的流程就是:

  1. 定义 configJson 配置
  2. 配置 Vite 插件
  3. 安装运行时插件
  4. 在组件中使用 useTemplateValue 取值
  5. 按需注册 registerTemplateFunction 暴露联动能力

现在你可以继续阅读configJson 结构页面取值,了解字段类型、媒体字段和数组字段的写法。