默认布局
那些放在layouts/目录下的.vue文件会被自动加载进来,如果我们创建的.vue名为default.vue,将会被用于项目所有页面中作为布局模板。
layouts/default.vue:
<template>
<div>
default.vue:
<slot />
</div>
</template>
这样页面就会直接出现default.vue文件内的内容了。
自定义布局
如果我们的布局文件名不叫default,而是别的,比如custom.vue,想要使用它们,就必须在某个页面中设置页面属性layout。
layouts/custom.vue:
<template>
<div>
custom.vue!
<slot />
</div>
</template>
然后你的其他页面那些需要用直接写如下代码就可以。
<script>
export default {
layout: "custom"
}
</script>
注意嵌套路由中是没有效果的
使用NuxtLayout
可以使用NuxtLayout组件结合slots获得完全控制力,同时需要设置组件选项layout: false。
helloworld.vue
<template>
<NuxtLayout name="custom">
<template #header>
<h1>hello page</h1>
</template>
some content...
</NuxtLayout>
</template>
<script>
export default {
layout: false,
};
</script>
修改一下custom.vue
<template>
<div>
内容来自自定义布局页custom.vue!
<slot name="header"/>
<slot />
</div>
</template>
我们甚至能组合多个布局页:
<template>
<div>
<NuxtLayout name="custom">
<template #header>
<h1>hello page</h1>
</template>
some content...
</NuxtLayout>
<NuxtLayout name="default">
some content...
</NuxtLayout>
</div>
</template>
配合
由于需要设置layout选项,所以在这个script标签旁边同时使用
<script>
export default {
layout: "custom",
};
</script>
<script setup>
// your setup script
</script>