进阶用法
深入了解 SDK 的高级功能和使用场景。
类型推导
SDK 提供 TypeScript 类型推导支持。通过 InferTemplateValueMap 类型,可以从 configJson 推导页面可读取的字段值类型。
import { defineTemplateConfig } from 'auto-exhibition-template-sdk/config'
import type { InferTemplateValueMap } from 'auto-exhibition-template-sdk'
const configJson = defineTemplateConfig({
meta: { name: 'demo' },
dataSchema: {
fields: [
{ key: 'title', type: 'string', value: 'Hello' }
]
}
})
// 自动推导类型
type ValueMap = InferTemplateValueMap<typeof configJson>
// { title: string }
配置校验
使用 validateTemplateConfig 函数可以在运行时校验配置是否符合规范。
import { validateTemplateConfig } from 'auto-exhibition-template-sdk'
const issues = validateTemplateConfig({
dataSchema: {
fields: [
{ key: 'title', type: 'string' }
]
}
})
if (issues.length > 0) {
console.error('配置校验失败', issues)
}
嵌套数组取值
对于数组中的 object 字段,可以使用下标和点路径组合读取。
configJson 示例
{
"dataSchema": {
"fields": [
{
"key": "models",
"type": "array",
"value": [
{
"type": "object",
"value": [
{ "key": "name", "type": "string" },
{ "key": "url", "type": "file" }
]
}
]
}
]
}
}
取值方式
const models = useTemplateValue('models', [])
const firstModel = useTemplateValue('models[0]', {})
const firstModelUrl = useTemplateValue('models[0].url', '')
媒体对象
image 和 video 字段在页面中读取为媒体对象,而不是字符串路径。
{
"url": "/assets/poster.png",
"poster": "/assets/poster-thumb.png"
}
在模板中使用
<template>
<img :src="poster.url" />
<video :src="trailer.url" :poster="trailer.poster">
</video>
</template>
自定义构建配置
templateSdkPlugin 支持传入额外的构建配置选项。
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import configJson from './config'
import { templateSdkPlugin } from 'auto-exhibition-template-sdk/vite'
export default defineConfig({
plugins: [
templateSdkPlugin({
configJson
// 可以添加更多配置选项
}),
vue()
]
})
模板函数和 Bridge
模板函数调用建立在本地 Bridge 之上。SDK 默认使用 ws://127.0.0.1:5176 连接客户端 Bridge,Bridge 再把函数调用转给网关或本地其他模板页。
import {
registerTemplateFunction,
invokeTemplateFunction
} from 'auto-exhibition-template-sdk'
registerTemplateFunction('showDetail', async (args) => {
currentId.value = args.id
return { ok: true }
})
await invokeTemplateFunction(
{ mode: 'binding', sourceFunction: 'showDetail' },
'showDetail',
{ id: 'item-01' }
)
需要本地调试时,使用 { mode: 'local' } 可以在同一设备多个模板页之间调用,不经过网关。
硬件扩展
网关侧已经预留 HardwareAdapter 模型。模板函数规则的目标可以是模板 endpoint,也可以是硬件 endpoint。SDK 不直接操作串口、MQTT 或 HTTP 硬件协议,硬件细节应放在网关 adapter 中。
[
{
"endpointType": "hardware",
"hardwareId": "mock-hardware",
"functionName": "echo"
}
]
调试技巧
在开发过程中,可以通过以下方式进行调试:
查看运行时值
const title = useTemplateValue('title', '')
// 在控制台查看
console.log('title value:', title.value)