<ClientOnly>
使用 <ClientOnly> 組件僅在客戶端渲染組件。
<ClientOnly>
組件用於特意僅在客戶端渲染組件。
預設插槽的內容將會在伺服器建置時被 tree-shaken 移除。(這確實表示當渲染初始 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>
在瀏覽器中掛載之前顯示。
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>
範例
存取 HTML 元素
<ClientOnly>
內部的組件僅在掛載後才會渲染。若要存取 DOM 中渲染的元素,您可以監看模板 ref
pages/example.vue
<script setup lang="ts">
const nuxtWelcomeRef = ref()
// 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>