- 基本概念
- layouts是Nuxt3提供的一种方便开发者快速实现自定义布局的约定
- 使用该约定需要在根目录下创建layouts文件夹,并在里面创建.vue文件用来作为布局模板。如果需要创建多个模板,在layouts中创建多个.vue文件即可
- 在layouts中创建的.vue文件可以看做是一个容器,我们需要使用
<slot name="header-box"/>
插槽来存放页面相应位置的填充内容 <NuxtLayout/>
标签是可以个通用的布局标签,可以看做我们创建的布局容器,可以<NuxtLayout name="xxx"/>
通过指定name
属性布局模板文件名的方式指定布局模板- 在
<NuxtLayout/>
标签中使用<template #header-box>
来为当前内容指定放置的布局位置。
- 实践练习
- 目标:实现一个类似vitepress文档页面的两栏布局
- 目录结构:
- custom.vue:
<template> <div class="page-box"> <div class="header-box"> <slot name="header-box"/> </div> <div class="body-box"> <div class="left-sider"> <slot name="left-sider"/> </div> <div class="body-content"> <slot name="body-content"/> </div> </div> </div> </template> <style> .page-box { display: flex; flex-direction: column; } .header-box { width: 100%; height: 100px; display: flex; background-color: red; } .body-box { width: 100%; display: flex; flex-flow: row; } .left-sider { width: 400px; height: calc(100vh - 100px); background: yellow; overflow: auto; } .body-content { flex: 1; height: calc(100vh - 100px); background-color: blue; overflow: auto; } .sider-content { height: 1300px; width: 200px; background-color: black; } </style>
- layout-test/index.vue:
<template> <NuxtLayout name='custom'> <template #header-box> <div>首页</div> <div>关于</div> </template> <template #left-sider> <div>快速入门</div> <div>使用</div> <div>目录结构</div> </template> <template #body-content> <div>我应该显示一点内容</div> </template> </NuxtLayout> </template> <script> export default { layout: false } </script>
- 在
pages/index.vue
中有一个跳转至layout-test/index.vue
的<NuxtLink/>
- Point
- 在Layouts中创建的default.vue会作为一个全局默认的布局模板
- 使用
<NuxtLayout>
标签时需要将当前页面的layout
设置为false,使用这种方式同时需要使用setup
时则需要额外创建一个<script setup>
- 当程序只有一种布局时,甚至可以直接在app.vue中创建布局
原文:https://juejin.cn/post/7038957796351541261