<ClientOnly>

仅在客户端使用 <ClientOnly> 组件渲染组件。

<ClientOnly> 组件用于在客户端渲染组件。

¥The <ClientOnly> component is used for purposely rendering a component only on client side.

默认插槽的内容将从服务器构建中摇树移除。(这意味着在渲染初始 HTML 时,其中组件使用的任何 CSS 都可能不会内联。)

Props

  • placeholderTag | fallbackTag:指定要在服务器端渲染的标签。
  • placeholder | fallback:指定要在服务器端渲染的内容。
<template>
  <div>
    <Sidebar />
    <!-- The <Comment> component will only be rendered on client-side -->
    <ClientOnly fallback-tag="span" fallback="Loading comments...">
      <Comment />
    </ClientOnly>
  </div>
</template>

插槽

¥Slots

  • #fallback:指定要在服务器上渲染并显示的内容,直到 <ClientOnly> 被挂载到浏览器中。
pages/example.vue
<template>
  <div>
    <Sidebar />
    <!-- This renders the "span" element on the server side -->
    <ClientOnly fallbackTag="span">
      <!-- this component will only be rendered on client side -->
      <Comments />
      <template #fallback>
        <!-- this will be rendered on server side -->
        <p>Loading comments...</p>
      </template>
    </ClientOnly>
  </div>
</template>

示例

¥Examples

访问 HTML 元素

¥Accessing HTML Elements

<ClientOnly> 中的组件仅在挂载后才会渲染。要访问 DOM 中已渲染的元素,你可以监视模板引用:

¥Components inside <ClientOnly> are rendered only after being mounted. To access the rendered elements in the DOM, you can watch a template ref:

pages/example.vue
<script setup lang="ts">
const nuxtWelcomeRef = useTemplateRef('nuxtWelcomeRef')

// The watch will be triggered when the component is available
watch(nuxtWelcomeRef, () => {
 console.log('<NuxtWelcome /> mounted')
}, { once: true })
</script>

<template>
  <ClientOnly>
    <NuxtWelcome ref="nuxtWelcomeRef" />
  </ClientOnly>
</template>