<ClientOnly>

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

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

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

属性

  • 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>

插槽

  • #fallback: 指定一个在服务器上渲染并显示的内容,直到 <ClientOnly> 在浏览器中挂载。
app/pages/example.vue
<template>
  <div>
    <Sidebar />
    <!-- This renders the "span" element on the server side -->
    <ClientOnly fallback-tag="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>

示例

访问 HTML 元素

<ClientOnly> 内部的组件仅在挂载后渲染。要访问 DOM 中渲染的元素,您可以监听一个模板引用。

app/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>