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