布局

布局目录

可以将常见的 UI 或代码提取到可重用的布局组件中使用;布局组件放在layouts/目录下,使用时通过异步导入自动加载。

在页面中通过 <NuxtLayout> 标签使用布局组件;

默认布局

layouts/ 目录下名称为 default.vue 的文件为默认布局组件;所有的布局组件中都需要提供一个插槽,用于指定页面在布局中的位置,如下:

<template>
    <div>
      默认布局
      <slot />
    </div>
</template>

如下,在页面中使用布局:

<template>
  <NuxtLayout>
    这是页面内容,将插入到布局文件中  
  </NuxtLayout>
</template>

自定义布局

如果需要使用自义布局,就要在使用时指定布局组件的名称,如下,使用 layout/customAb.vue 布局组件:

<template>
  <NuxtLayout name="custom-ab">
    这是页面内容,将插入到布局文件中  
  </NuxtLayout>
</template>

布局插槽

布局组件:

<template>
    <div>
      这是布局
      <slot />
      <slot name="header">插槽的默认内容</slot>
    </div>
</template>

使用页面:使用时要将 layout 设置为 false,如下:

<template>
    <div>
        <NuxtLayout name="custom-ab">
            <template #header>
                这是插槽内容
            </template>
            这是页面内容
        </NuxtLayout>
    </div>
</template>

<script setup>
definePageMeta({
  layout: false,
});
</script>

注意事项

1.0> <NuxtLayout> 标签不能作为页面根元素;

2.0> 布局组件命名为小驼峰,但使用时会默认转为短横线,如:someLayout会变为some-layout

3.0> 布局组件必须有一个根元素以允许 Nuxt 在布局更改之间应用过渡,并且根元素不能是<slot />。

官网

https://v3.nuxtjs.org/guide/directory-structure/layouts

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容