<ClientOnly> 组件专门用于仅在客户端渲染组件。
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> 在浏览器中挂载。<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>
<ClientOnly> 内部的组件仅在挂载后渲染。要访问 DOM 中渲染的元素,您可以监听一个模板引用。
<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>