useFetchComponentExample

读取 components/content/examples 下示例组件的源码、文件路径与组件名。ComponentExample 用它展示示例代码,需要在自定义组件中显示示例源码时直接调用。仅在开启组件文档功能时可用。

useFetchComponentExample() 请求 /api/component-example/{name}.json,返回 useAsyncData 的结果。示例源码在构建期从 components/content/examples 收集,服务端按 PascalCase 名称查找。

需要在 nuxt.config 中设置 movkNuxtDocs.componentDocs: true,见 功能开关。关闭时该函数不会被自动导入。

用法

<script setup lang="ts">
const { data: example } = await useFetchComponentExample('ButtonExample')
</script>

<template>
  <UCodeBlock v-if="example?.code" :code="example.code" language="vue" />
</template>

签名

function useFetchComponentExample(name: string): AsyncData<Partial<ComponentExampleData> | undefined, NuxtError | undefined>

interface ComponentExampleData {
  code: string
  filePath: string
  pascalName: string
}

参数

名称类型说明
namestring示例组件名,服务端会转为 PascalCase 后查找,button-example、buttonExample、ButtonExample 等价

返回值

名称类型说明
dataRef<Partial<ComponentExampleData> | undefined>code 为示例源码,filePath 为源文件路径,pascalName 为组件名;找不到示例时为空对象
statusRef<AsyncDataRequestStatus>请求状态
refresh() => Promise<void>重新请求

客户端调用时为懒加载,模板中要做空值判断。

相关

更新日志

No recent changes
Copyright © 2024 - 2026