Nuxt3(beat)—layouts的使用

  • 基本概念
  1. layouts是Nuxt3提供的一種方便開發者快速實現自定義佈局的約定
  2. 使用該約定需要在根目錄下創建layouts文件夾,並在裏面創建.vue文件用來作爲佈局模板。如果需要創建多個模板,在layouts中創建多個.vue文件即可
  3. 在layouts中創建的.vue文件可以看做是一個容器,我們需要使用<slot name="header-box"/>插槽來存放頁面相應位置的填充內容
  4. <NuxtLayout/>標籤是可以個通用的佈局標籤,可以看做我們創建的佈局容器,可以<NuxtLayout name="xxx"/>通過指定name屬性佈局模板文件名的方式指定佈局模板
  5. <NuxtLayout/>標籤中使用<template #header-box>來爲當前內容指定放置的佈局位置。
  • 實踐練習
  1. 目標:實現一個類似vitepress文檔頁面的兩欄佈局
  2. 目錄結構
  1. 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>
  1. 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>
  1. pages/index.vue中有一個跳轉至layout-test/index.vue<NuxtLink/>
  • Point
  1. 在Layouts中創建的default.vue會作爲一個全局默認的佈局模板
  2. 使用<NuxtLayout>標籤時需要將當前頁面的layout設置爲false,使用這種方式同時需要使用setup時則需要額外創建一個<script setup>
  3. 當程序只有一種佈局時,甚至可以直接在app.vue中創建佈局

    原文:https://juejin.cn/post/7038957796351541261

 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章