Nuxt3。动态布局变化

问题描述 投票:0回答:2

我想在人们通过直接链接进入网站时动态切换布局并加载所需的布局。

我使用指南(v3.nuxtjs.org/guide),它说添加以下代码

const route = useRoute()
function enableCustomLayout() {
   route.meta.layout = "custom"
}
definePageMeta({
   layout: false
});

这解决了网站加载时的问题,但又产生了另一个问题。网站加载时,布局需要很长时间才能加载。

Lag gif

如何解决这个问题并达到预期的效果?

我使用示例代码创建了一个 stackblitz 项目

layout nuxt.js vuejs3 nuxtjs3
2个回答
0
投票

建议使用

definePageMeta

https://nuxt.com/docs/api/utils/define-page-meta

使用

NuxtLayout

// ~/app.vue
<template>
  <div>
    <NuxtLayout>
      <NuxtPage />
    </NuxtLayout>
  </div>
</template>

如果未指定布局,将加载名为

layouts
default
文件夹中的文件。

// ~/layouts/default.vue
<template>
  <h1>Default Layout</h1>
  <slot />
</template>

使用任意名称创建更多布局...

// ~/layouts/custom.vue
<template>
  <h1>My Custom Layout</h1>
  <slot />
</template>

在内容页面中使用

definePageMeta
指定与
layout
目录中布局的文件名匹配的
layouts
名称。

// ~/pages/index.vue

<script setup>
definePageMeta({
  layout: 'custom'
})
</script>

<template>

  <div>
    Content page using specific layout
  </div>

</template>

https://nuxt.com/docs/guide/directory-struct/layouts


0
投票

在你的 app.vue 中你可以做类似的事情

  <script setup lang="ts">
  
  const userLayout = "user";
  const adminLayout = "admin";
  const propertiesLayout = "properties";
  // check route and set layout
  const route = useRoute();
  const layout = computed(() => {
    if (route.path.includes("/admin")) {
      return adminLayout;
    } else if (route.path.includes("/properties")) {
      return propertiesLayout;
    } else {
      return userLayout;
    }
  });

  </script>
<template>
  
  <NuxtLayout :name="layout"> </NuxtLayout>
</template>
<style > </style>
© www.soinside.com 2019 - 2024. All rights reserved.