如何在Nuxt 3中应用动态布局?

huangapple go评论60阅读模式
英文:

How to apply dynamic layouts in Nuxt 3?

问题

/pages
  /item
    [id].vue
/layouts
  default.vue
  FooLayout.vue
  BarLayout.vue
  BazLayout.vue
我有一个简单的Nuxt 3项目,其中包括动态页面和一些自定义布局:

我想根据不同的“item组”应用自定义布局,类似于这样:

### entities.json
```json
{
  1: 'FooLayout',
  2: 'BarLayout',
  3: 'BazLayout'
}

dataset.json

[
  {
    "id": 1,
    "group": 1,
    ...
  }
]

[id].vue

<script setup>
import items from '~/assets/static/dataset.json';
import { GROUPS } from '~/assets/entities.json';
const route = useRoute();

const params = route.params;
const ITEM_ID = params.itemId;

const item = items.find((item) => item.id == ITEM_ID);

const LAYOUT_GROUP = GROUPS[item.group];

definePageMeta({
  layout: LAYOUT_GROUP // &lt;-- 期望是: 'FooLayout'
});
</script>

<template>
  <div>
   {{ item }}
  </div>
</template>

但现在我看到以下错误消息,我不知道如何根据“LAYOUT_GROUP”应用自定义布局:

错误:

Uncaught ReferenceError: LAYOUT_GROUP is not defined

方法 2:

如果我使用 <NuxtLayout :name="LAYOUT_GROUP">

我会看到以下警告:

Invalid layout FooLayout selected.


<details>
<summary>英文:</summary>

I have a simple Nuxt 3 project with dynamic pages and some custom layouts:

/pages
/item
[id].vue


/layouts
default.vue
FooLayout.vue
BarLayout.vue
BazLayout.vue


I want to apply custom layouts based on a different `item group`, something like this:

### entities.json
```json
{
  1: &#39;FooLayout&#39;,
  2: &#39;BarLayout&#39;,
  3: &#39;BazLayout&#39;
}

dataset.json

[
  {
    &quot;id&quot;: 1,
    &quot;group&quot;: 1,
    ...
  }
]

[id].vue

&lt;script setup&gt;
import items from &#39;~/assets/static/dataset.json&#39;;
import { GROUPS } from &#39;~/assets/entities.json&#39;;
const route = useRoute();

const params = route.params;
const ITEM_ID = params.itemId;

const item = items.find((item) =&gt; item.id == ITEM_ID);

const LAYOUT_GROUP = GROUPS[item.group];

definePageMeta({
  layout: LAYOUT_GROUP // &lt;-- expected to be: &#39;FooLayout&#39;
});
&lt;/script&gt;

&lt;template&gt;
  &lt;div&gt;
   {{ item }}
  &lt;/div&gt;
&lt;/template&gt;

But now I see the following error message and don't know how I can apply a custom layout based on the LAYOUT_GROUP:

Error:

> Uncaught ReferenceError: LAYOUT_GROUP is not defined

Approach 2:

if I'm using &lt;NuxtLayout :name=&quot;LAYOUT_GROUP&quot;&gt;

I will see the following warning:

> Invalid layout FooLayout selected.

答案1

得分: 0

我看到布局名称必须以小写字母开头,或者采用kebab-case格式,就像文档中提到的

布局名称被规范化为 kebab-case

我无法通过definePageMeta来实现它。仍然会出现未定义的错误。

但是通过:name="&#39;foo&#39;"可以工作。

英文:

Alright, I see the layout name must be start as lowercase, or be in kebab-case, like the documentation mentioned:

> The layout name is normalized to kebab-case

I couldn't implement it with definePageMeta. There comes still the not defined error.

But with :name=&quot;&#39;foo&#39;&quot; it works.

huangapple
  • 本文由 发表于 2023年2月6日 20:04:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/75361083.html