<ClientOnly>

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

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

默认插槽的内容将会在服务端构建中被 tree-shake 掉。(这也意味着其中组件使用的任何 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 中渲染出的元素,可以监听一个模板引用(template ref):

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>