
Nuxt 官网地址:https://nuxt.com/
Nuxt 提供多个组件层来实现应用程序的用户界面。
下面逐一进行介绍。
默认情况下,Nuxt 会将 app.vue 文件视为入口点,并在应用程序的每个路由中呈现其内容。下面的代码片段是 app.vue 文件的基础代码结构:
// App.vue
<template>
<div>
<h1>Welcome to the homepage</h1>
</div>
</template>
如果您熟悉 Vue,可能会想知道 main.js 在哪里(通常创建 Vue 应用程序的文件)。Nuxt 在幕后完成了这项工作。
大多数组件都是用户界面中可重复使用的部分,如按钮和菜单。在 Nuxt 中,您可以在 components/ 目录中创建这些组件,它们将自动在您的应用程序中可用,而无需显式导入。
AppAlert的组件,应用启动后,它就被自动加载,无需导入即可使用。// components/AppAlert.vue
<template>
<span class="warning">
<slot />
</span>
</template>
<style scoped>
.warning {
color: orange;
}
</style>
// app.vue
<template>
<div>
<h1>Welcome to the homepage</h1>
<AppAlert>AppAlert Component.</AppAlert>
</div>
</template>
页面代表每个特定路由模式的视图。pages/ 目录中的每个文件都代表了显示其内容的不同路由。
通过在 pages/ 目录下创建 .vue 文件以创建更多页面及其相应路由,并在 app.vue 中添加 <NuxtPage /> 组件来加载匹配当前路由模式的。
下面创建两个页面做示例:
<template>
<div>
<h1>@ index page</h1>
<AppAlert>AppAlert Component.</AppAlert>
</div>
</template>
<template>
<div>
<h1>@ about page</h1>
<AppAlert>AppAlert Component.</AppAlert>
</div>
</template>
创建的页面如何通过路由访问呢?此处先做简单介绍,后续会写一篇专门介绍路由的文章。
pages:true<NuxtPage /> 组件来展示请求的路由对应文件内容。http://localhost:3000 就展示 index.vue 的内容,访问 http://localhost:3000/about 就展示 about.vue 的内容注意:pages/index.vue 只能通过
http://localhost:3000来访问,不能通过http://localhost:3000/index访问(访问会报 404 错)。
布局是围绕包含多个页面的公共用户界面的页面的包装器,例如页眉和页脚显示。
布局是使用
布局被放置在 layouts/目录中,使用时将通过异步导入自动加载。
如果您的应用程序中只有一个布局,我们建议您使用带有 NuxtPage 组件的 app.vue 代替。
默认布局的使用方法是将 <NuxtLayout> 添加到 app.vue 中。(更多自定义布局使用方法后续会写专篇文章来做分享)
// layouts/default.vue
<template>
<div>
<div class="header">header Block</div>
<slot />
<div class="footer">footer Block</div>
</div>
</template>
<style scoped>
.header {
border-bottom: 1px solid #e0e0e0;
text-align: center;
}
.footer {
border-top: 1px solid #e0e0e0;
text-align: center;
}
</style>
需要在 app.vue 文件中添加 <NuxtLayout> 组件:
// app.vue
<template>
<div>
<NuxtLayout>
<NuxtPage />
</NuxtLayout>
</div>
</template>
此时再访问 http://localhost:3000 和 http://localhost:3000/about 就可以看到 layout 的效果了。
🔥BuildAdmin是一个永久免费开源,无需授权即可商业使用,且使用了流行技术栈快速创建商业级后台管理系统。