基础使用示例
这是一个完整的基础使用示例,展示了如何使用 template-sdk 从配置到组件取值的完整流程。
项目结构
src/
├── template/
│ └── config.ts // 模板配置
├── components/
│ └── HeroSection.vue // 使用 SDK 的组件
├── App.vue
├── main.ts
└── vite.config.ts
第一步:定义配置
创建 src/template/config.ts 文件:
// src/template/config.ts
import { defineTemplateConfig } from 'template-sdk/config'
const configJson = defineTemplateConfig({
meta: {
name: '示例模板',
code: 'demo-template',
version: '1.0.0'
},
dataSchema: {
fields: [
{
key: 'title',
type: 'string',
label: '主标题',
value: '欢迎使用 template-sdk'
},
{
key: 'subtitle',
type: 'string',
label: '副标题',
value: '面向模板项目的前端 SDK'
}
]
},
functions: {}
})
export default configJson
第二步:配置 Vite 插件
在 vite.config.ts 中启用插件:
// vite.config.ts
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import configJson from './src/template/config'
import { templateSdkPlugin } from '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 '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 'template-sdk'
// 读取标题字段,提供空字符串作为兜底值
const title = useTemplateValue('title', '默认标题')
// 读取副标题字段
const subtitle = useTemplateValue('subtitle', '')
</script>
<template>gt;
<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>
效果预览
运行 pnpm dev 后,你将看到:
欢迎使用 template-sdk
面向模板项目的前端 SDK
总结
完整的流程就是:
- 定义 configJson 配置
- 配置 Vite 插件
- 安装运行时插件
- 在组件中使用 useTemplateValue 取值