useFetchComponentExample

Read the source code, file path and name of example components under components/content/examples. ComponentExample uses it to show example code; call it directly to display example source in your own components. Available only with component docs enabled.

useFetchComponentExample() requests /api/component-example/{name}.json and returns the result of useAsyncData. Example sources are collected from components/content/examples at build time, and the server looks them up by PascalCase name.

Set movkNuxtDocs.componentDocs: true in nuxt.config, see Feature Flags. When disabled, the function is not auto-imported.

Usage

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

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

Signature

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

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

Parameters

NameTypeDescription
namestringExample component name; the server converts it to PascalCase, so button-example, buttonExample and ButtonExample are equivalent

Return Value

NameTypeDescription
dataRef<Partial<ComponentExampleData> | undefined>code is the example source, filePath the source file path, pascalName the component name; an empty object when no example is found
statusRef<AsyncDataRequestStatus>Request status
refresh() => Promise<void>Request again

On the client the call is lazy; guard against empty data in templates.

Changelog

No recent changes
Copyright © 2024 - 2026