###概述
components/ 目录是放置 Vue 组件的位置,Nuxt会自动导入components/目录中的所有组件;
a. 组件命名:
| components/
--| TheHeader.vue
--| TheFooter.vue
b. 在页面中使用组件:(Nuxt会自动按需导入组件)
<template>
<div>
<TheHeader />
<TheFooter />
</div>
</template>
###组件名称 组件的使用名称必须与组件名称完全相同,Nuxt不会做大驼峰转短横线这种操作; 如果组件嵌套在目录中,则组件的使用名称是其目录名称的大驼峰拼接(删除重复的段),如下:
| components/
--| base/
----| foo/
------| Button.vue
使用组件:
<BaseFooButton />
###动态组件
<template>
<component :is="clickable ? MyButton : 'div'" />
</template>
<script setup>
const MyButton = resolveComponent('MyButton')
</script>
resolveComponent用于处理动态组件,该组件名称必须是字符串而不是变量。
###动态导入
在组件名称前加Lazy前缀,即可实现动态组件;
使用时在页面中动态显示该组件,该组件才会从服务端进行异步加载,如下:
// 组件
| components/
--| LazyMountainsList.vue
// 使用
<LazyMountainsList v-if="show" />
###组件
<ClientOnly>组件仅客户端才渲染其插槽中的内容,如下:
<template>
<div>
<ClientOnly>
<!-- 这个组件只会在客户端渲染 -->
<Comments />
</ClientOnly>
</div>
</template>
client 组件
如果组件仅在客户端呈现,则可以将.client后缀添加到组件中,如下;
//组件
| components/
--| Comments.client.vue
//使用
<template>
<div>
<!-- 这个组件只会在客户端渲染 -->
<Comments />
</div>
</template>
###.server 组件
.server组件是.client组件的后备组件,可用于在.client组件加载过程中显示loading内容:
//组件
| components/
--| Comments.client.vue
--| Comments.server.vue
// 使用
<template>
<div>
<!-- 该组件在服务器端渲染Comments.server,然后在客户端加载 Comments.client -->
<Comments />
</div>
</template>
注:实测项目重启后.server组件才能生效;
###组件
<DevOnly>组件仅在开发过程才渲染其插槽中的内容,如下:
<template>
<div>
<DevOnly>
<!-- 这个组件只会在开发过程中渲染 -->
<LazyDebugBar />
</DevOnly>
</div>
</template>
###注意项目
所有只有客户端才渲染的组件都异常加载; 动态组件只是组件的切换,并不是异常加载; 动态加载是异步组件;