页面取值

在 Vue 组件中使用 useTemplateValue 读取 configJson 中声明的字段,路径写法与字段层级保持一致。

基础用法

useTemplateValue 接收字段路径和可选兜底值,返回可在模板中直接使用的响应式值。

<script setup>
import { useTemplateValue } from 'auto-exhibition-template-sdk'

const title = useTemplateValue('title', '')
const enabled = useTemplateValue('enabled', false)
</script>

<template>
  <h1>{{ title }}</h1>
  <p>{{ enabled ? '已启用' : '未启用' }}</p>
</template>

路径规则

  • 根字段使用字段 key,例如 title
  • object 子字段使用点路径,例如 profile.name
  • array 子项使用下标,例如 models[0]
  • 数组中的 object 子字段可以继续使用点路径,例如 models[0].url
  • 不使用以 / 开头的路径
路径 说明
title 读取根级字段
profile.name 读取 object 字段中的子字段
models 读取整个模型数组
models[0] 读取模型数组第一项
models[0].url 读取模型数组第一项的文件路径

读取 object

object 字段会在页面中表现为普通对象。可以读取整个对象,也可以读取某个子字段。

const profile = useTemplateValue('profile', {})
const name = useTemplateValue('profile.name', '')

读取媒体和文件

image 和 video 字段读取为媒体对象,常用 url 渲染资源;file 字段读取为文件路径字符串。

const poster = useTemplateValue('poster', null)
const trailer = useTemplateValue('trailer', null)
const modelFile = useTemplateValue('modelFile', '')
<template>
  <img :src="poster?.url" />
  <video :src="trailer?.url" :poster="trailer?.poster" controls />
</template>

读取数组

当 array 的第一项是匿名 object 模板时,页面中读取到的是对象数组,适合模型列表、展项列表等可增删内容。

{
  "key": "models",
  "type": "array",
  "value": [
    {
      "type": "object",
      "value": [
        { "key": "name", "type": "string", "value": "Meteor Shower" },
        { "key": "url", "type": "file", "value": "/assets/models/demo.glb" }
      ]
    }
  ]
}
<script setup>
import { useTemplateValue } from 'auto-exhibition-template-sdk'

const models = useTemplateValue('models', [])
</script>

<template>
  <ul>
    <li v-for="model in models" :key="model.url">
      {{ model.name }}: {{ model.url }}
    </li>
  </ul>
</template>
数组提示:
  • 数组项模板可以省略 key,因为数组项按索引读取
  • 后台新增数组项时使用第一项的结构,新值会按字段类型置空
  • 如果 array.value 是空数组,后台无法判断新增项结构

SDK 元信息:__templateSdk

0.2.0 开始,构建出的 valueMap.json 会自动包含 __templateSdk。它用于保存 SDK 版本化元信息,目前包含模板函数 manifest。

{
  "title": "主屏播放",
  "__templateSdk": {
    "schemaVersion": 1,
    "functions": {
      "playVideo": {
        "name": "playVideo",
        "label": "播放视频",
        "direction": "inout",
        "params": [
          { "name": "id", "type": "string", "required": true }
        ]
      }
    }
  }
}

后台和网关可以读取 valueMap.__templateSdk.functions 来知道当前模板暴露了哪些函数。模板页面一般不需要直接渲染这个字段。