useTemplateValue
useTemplateValue 是 SDK 的核心组合式函数,用于在 Vue 组件中读取模板字段值。
导入
import { useTemplateValue } from 'template-sdk'
类型签名
function useTemplateValue<Path extends TemplateValuePath>(
path: Path,
fallback?: TemplateValueAtPath<Path>
): Ref<TemplateValueAtPath<Path>>
参数
| 参数名 | 说明 | 类型 | 必填 |
|---|---|---|---|
path |
字段路径,支持点路径语法 | string |
是 |
fallback |
兜底值,当路径没有取到值时返回 | any |
否 |
返回值
返回一个 Ref<T>,可直接在 Vue 模板中响应式使用。
路径语法
useTemplateValue 只接受点路径语法:
| 路径示例 | 说明 |
|---|---|
'title' |
读取根级 string/number/boolean 字段 |
'poster' |
读取根级 image/video 字段,返回媒体对象 |
'timeline' |
读取根级 array 字段 |
'timeline[0]' |
读取数组第一项 |
'timeline[0].phase' |
读取数组第一项的子字段 |
注意:
不接受以
/ 开头的旧写法。
使用示例
基础用法
<script setup>
import { useTemplateValue } from 'template-sdk'
// 读取字符串字段
const title = useTemplateValue('title', '默认标题')
// 读取数字字段
const count = useTemplateValue('count', 0)
// 读取布尔字段
const enabled = useTemplateValue('enabled', false)
</script>
<template>gt;
<h1>{{ title }}</h1>
<p>{{ count }}</p>
<p>{{ enabled ? '启用' : '禁用' }}</p>
</template>
图片字段
image 字段返回媒体对象,包含 url、alt、poster 等属性。
<script setup>
import { useTemplateValue } from 'template-sdk'
const poster = useTemplateValue('poster', null)
</script>
<template>gt;
<img
:src="poster?.url"
:alt="poster?.alt"
class="poster"
/>
</template>
视频字段
<script setup>
import { useTemplateValue } from 'template-sdk'
const trailer = useTemplateValue('trailer', null)
</script>
<template>gt;
<video
:src="trailer?.url"
:poster="trailer?.poster"
controls
>
</video>
</template>
数组字段
<script setup>
import { useTemplateValue } from 'template-sdk'
const timeline = useTemplateValue('timeline', [])
</script>
<template>gt;
<div v-for="(item, index) in timeline" :key="index">
<p>{{ item.phase }}</p>
</div>
</template>
嵌套数组取值
<script setup>
import { useTemplateValue } from 'template-sdk'
// 读取嵌套数组的特定项
const firstPhase = useTemplateValue('timeline[0]')
const secondPhaseText = useTemplateValue('timeline[1].phase')
</script>
<template>gt;
<p>{{ firstPhase }}</p>
<p>{{ secondPhaseText }}</p>
</template>
运行时值类型
不同类型的字段在运行时的值类型:
| configJson 类型 | 运行时值类型 |
|---|---|
string |
string |
number |
number |
boolean |
boolean |
image |
TemplateMediaObject |
video |
TemplateMediaObject |
array |
TemplateField[] |