英文:
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 // <-- 期望是: '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: '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 // <-- expected to be: 'FooLayout'
});
</script>
<template>
<div>
{{ item }}
</div>
</template>
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 <NuxtLayout :name="LAYOUT_GROUP">
I will see the following warning:
> Invalid layout FooLayout
selected.
答案1
得分: 0
我看到布局名称必须以小写字母开头,或者采用kebab-case格式,就像文档中提到的:
布局名称被规范化为 kebab-case
我无法通过definePageMeta
来实现它。仍然会出现未定义的错误。
但是通过:name="'foo'"
可以工作。
英文:
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="'foo'"
it works.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论