Nuxt3 学习layout目录

2,811 阅读2分钟

「时光不负,创作不停,本文正在参加2021年终总结征文大赛

奉上一张本人的美女画作,试图收买官方,多多浏览,😁😁😁

前言

工作两年多了,第一次接触Nuxt框架,以此文章记录Nuxt3的学习历程,也与大家分享Nuxt3的知识点,并积极踩坑。Nuxt3的安装就不再赘述了,今天给大家介绍下Nuxt3的布局方式,因为Nuxt是基于约定式的SSR框架。因此开发时请注意规范命名,避免不必要的文件冲突。

Layouts目录

首先app.vue是Nuxt的核心入口文件,在其中增加内置组件NuxtPage作为路由出口后,同级目录增加pages文件夹,创建index.vue文件。便可以在页面中加载index.vue文件内容。

pages/index.vue代码

<template>
    <div style="height:500px;background:yellow;">
      Left
    </div>
    <div style="height:500px;background: red;">
      Right
    </div>
</template>

<script>
export default {
}
</script>

image.png 上图是添加pages/index.vue后的效果图,我们把这个页面定义成“内容页”,接下来给这个页面增加布局。

default布局

Nuxt3可以使用默认布局,方法是中根路径下新建layouts文件夹并新建default.vue文件。

<template>
<div style="display:flex;flex-direction:column;height:800px;">
  <div class="header">标题</div>
  <div class="container">
    <slot></slot>
  </div>
</div>
</template>

<style>
.header {
  height: 200px;
  background: blue;
}
.container {
  flex: 1 1 auto;
  background: #ccc;
  padding:20px;
}
</style>

image.png 页面效果图,需要加上slot才可以使page目录下的“内容页”加载。视图中的default.vue是一个上下布局(蓝色与灰色背景),如果我们还想自定义一个左右布局该怎么实现呢?

自定义布局

layouts文件夹下自定义一个vue文件,我创建为custom.vue

custom.vue文件内容

<template>
  <div>
      <h1>
      Some shared layout content:
  </h1>
  <div style="margin-top:20px;padding:20px;background:pink;">
   <slot name="header">
      <h2>自定义内容标题</h2>
    </slot>
  <div class="custom">
    <slot />
  </div>
    </div>
  </div>
</template>

<script>
export default {
}
</script>

<style>
.custom {
  width: 100%;
  display: flex;
  background: green;
}
.custom h1 {
  color: #ccc;
}
.custom div {
  flex: 1 1 auto;
}
</style>

接下来我们希望将这个布局方式作用在“内容页”中。这需要修改下“内容页”代码,如下

pages/index.vue内容

<template>
    <div style="height:500px;background:yellow;">
      Left
    </div>
    <div style="height:500px;background: red;">
      Right
    </div>
  
</template>

<script>
export default {
 layout: "custom"
}
</script>

image.png

效果图如上,在pages/目录下我们要加上custom布局的vue文件中增加layout属性,设置成与自定义布局文件相同的名称即可达到这样的效果,但这造成了一个新问题就是我们的default布局消失了,那如何在保持有default布局的前提下,在我们的“内容页”中有自定义布局呢?

插槽使用

我们修改pages/index代码如下

<template>
<NuxtLayout>
<NuxtLayout name="custom">
    <template #header>插槽标题</template>
    <div style="height:500px;background:yellow;">
      Left
    </div>
    <div style="height:500px;background: red;">
      Right
    </div>
  </NuxtLayout>
</NuxtLayout>
  
</template>

<script>
export default {
 layout: false
}
</script>

注意:layout属性改为false,并使用内置组件NuxtLayout,其使用方法与slot类型,不加name属性默认为default,页面如下: image.png 我们还可以在这个基础上在内容页中继续添加<NuxtLayout>(上下布局)和 <NuxtLayout name="custom">(左右布局)以此来递归调用组件,这里就不再赘述了。

Set up使用

最后因为我们要使用带layout属性的配置项<script>,所以可以再创建一个<script setup>使用Vue3的组合式API。

总结

layouts文件夹强制约定放置所有布局文件,并以插槽的形式作用在页面中。下一篇继续介绍pages文件夹