<ClientOnly>

原始檔
使用 <ClientOnly> 元件只在客戶端渲染元件。

<ClientOnly> 元件專門用於只在客戶端渲染元件。

預設插槽的內容將在伺服器構建中被 tree-shake 掉。(這意味著,在渲染初始 HTML 時,其中元件使用的任何 CSS 可能不會被內聯。)

屬性

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