<ClientOnly>
使用 <ClientOnly> 组件仅在客户端渲染组件。
The <ClientOnly> 组件专门用于仅在客户端上渲染组件。
默认插槽的内容将通过摇树优化(tree-shaking)从服务端构建中移除。(这意味着其中组件使用的任何 CSS 在渲染初始 HTML 时可能不会被内联。)
属性
placeholderTag|fallbackTag:指定要在服务端渲染的标签。placeholder|fallback:指定要在服务端渲染的内容。
app/pages/example.vue
<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>