Preface
An article on the server side rendering basis , introduced the advantages and disadvantages of various rendering modes, and in the end use vue.js
of Nuxt.js
by a small case, the experience of modern server rendering mode.
Nuxt.js definition
Nuxt.js
Is based on aVue.js
server-side rendering application framework, through the abstract organization of client / server infrastructure,Nuxt.js
the main concern is the UI rendering application, you can easily achieve homogeneous application- As a client/server framework, it provides many useful features:
- based on
Vue.js
- Automatic code layering
- Server-side rendering
- Powerful routing function, support asynchronous data
- Static file service
ES2015+
Grammar support- Packing and compression
JS
andCSS
- HTML head tag management
- Local development supports hot reloading
- integrated
ESLint
- Pre-processor supports a variety of
SASS
styles:LESS
, ,Stylus
etc. - Support
HTTP/2
Push
- based on
Nuxt.js use scope
Nuxt.js
Mainly used in the following situations:
- Use to
Nuxt.js
initialize a brand new project - For existing
node.js
server project, directlyNuxt
as a middleware integration intoNode Web Server
the - Solve the disadvantages of
Vue.js
slow loading of the first screen of existing projects and unfavorableSEO
defects. In this case, developers are requiredNuxt
to have a high degree of mastery, and the amount of code changes is large, at least 10% changes.
Create Nuxt project
Nuxt.js
There are two ways to create a project:
- Use the create-nuxt-app scaffolding tool
- Developers create manually, must follow the rules of Nuxt.js directory structure
Create a project manually, enter the project directory
# 初始化 package.json 文件
yarn init
# 安装 nuxt
yarn add nuxt
Added in the package.json
document scripts
:
"scripts": {
"dev": "nuxt" //可以通过运行npm run dev来运行nuxt
},
Create a new pages
directory, create the first pagepages/index.vue
<template>
<div>
<h1>Hello Nuxt.js</h1>
</div>
</template>
<script>
export default {
name: 'home'
}
</script>
<style>
</style>
Startup project
yarn dev
The application http://localhost:3000
is running on, check whether it can be accessed on the browser.
Note: Nuxt.js will monitor file changes in the pages directory, so there is no need to restart the application when adding new pages.
routing
Ordinary routing
The Vue.js
difference is that there is Nuxt.js
no need for the developer to explicitly define vue-router
routing rules in the project. The routing configuration of the module Nuxt.js
will be automatically generated based pages
on all the *.vue
files in the directory vue-router
, find the folder index.vue
and use it as the component of the root path of this folder .
pages
The directory structure is as follows:
pages/
--| user/
-----| index.vue
-----| info.vue
--| index.vue
Nuxt.js
The automatically generated routing configuration is as follows:
router: {
routes: [
{
name: 'index',
path: '/',
component: 'pages/index.vue'
},
{
name: 'user',
path: '/user',
component: 'pages/user/index.vue'
},
{
name: 'user-one',
path: '/user/info',
component: 'pages/user/info.vue'
}
]
}
Route navigation
Nuxt.js
Providing routing component nuxt-link
for a jump between pages, and its role router-link same through the to
target address attribute, a default tag rendered with the correct links can be configured tag
to generate another tag attributes.
<nuxt-link to="/">跳转到首页</nuxt-link>
Also supports navigation routing program, and method of use Vue.js
of the program navigation consistent
<button @click="onClick">跳转到首页</button>
methods: {
onClick() {
this.$router.push('/');
}
}
It also supports the use of <a></a>
tags for page jumps, but this method will refresh the page and send a request to the server, so it is not recommended.
Nested routing
Nuxt.js
Provides three ways to implement nested routing.
- By
vue-router
sub-routes createNuxt.js
a nested routing applications - In
nuxt.config.js
byextendRoutes
custom routing rules - Use
Nuxt.js
according topages
all directory*.vue
automatically generated filevue-router
routing module configuration rules, but the following two conditions need to be met:- Add a
.vue
file, while adding a directory with the same file name to store it in the sub-assembly view - Within parent components (
.vue
in the paper) to increase the content of a display sub-view (corresponding tovue.js
arouter-view
)
- Add a
As shown in the figure below, the parent component students.vue
, its child components are stored in the students
directory with the same name
Dynamic routing
By extendRoutes
custom set of routing rules, the dynamic routing rules vue matching with dynamic routing matching , in Nuxt.js
dynamic routing which defines parameters need to create corresponding to underscore prefixed Vue
files or directories.
The directory structure is as follows:
pages/
--| _slug/
-----| comments.vue
-----| index.vue
--| users/
-----| _id.vue
--| index.vue
Nuxt.js
The corresponding routing configuration table is generated as follows:
router: {
routes: [
{
name: 'index',
path: '/',
component: 'pages/index.vue'
},
{
name: 'users-id',
path: '/users/:id?',
component: 'pages/users/_id.vue'
},
{
name: 'slug',
path: '/:slug',
component: 'pages/_slug/index.vue'
},
{
name: 'slug-comments',
path: '/:slug/comments',
component: 'pages/_slug/comments.vue'
}
]
}
Custom routing configuration
base is used to nuxt.config.js
configure the root path of the application, for example:
//nuxt.config.js
module.exports = {
router: {
base: '/app' //默认路由改为http://localhost:3000/app/
}
}
extendRoutes extends the routes created by Nuxt.js or custom routing configuration rules. The following example configures custom routing table rules
//nuxt.config.js
module.exports = {
router: {
extendRoutes(routes, resolve) {
routes.splice(0);//清除nuxtjs根据Pages目录生成的默认路由
routes.push(...[
{
path: '/',
component: resolve(__dirname, 'pages/layout/'),
children: [
{
path: '', //默认子路由
name: 'home',
component: resolve(__dirname, 'pages/home/')
},
{
path: '/login',
name: 'login',
component: resolve(__dirname, 'pages/login/')
}
]
}
]);
}
}
}
view
Nuxt.js
The components of the view are shown in the following figure:
template
Nuxt.js
The default template is:
<!DOCTYPE html>
<html {
{
HTML_ATTRS }}>
<head {
{
HEAD_ATTRS }}>
{
{
HEAD }}
</head>
<body {
{
BODY_ATTRS }}>
{
{
APP }}
</body>
</html>
In the src
folder (default is the application root directory) to create a app.html
file you can customize the default html template.
layout
According to Nuxt.js
the catalog rules, if there are no additional configuration items in an application, the layout components must be written in the layout catalog layouts
.
- Default layout
By layouts/default.vue
extend the default layout of the application file, the file must be added <nuxt/>
component for displaying the main content of the page.
<template>
<div>
<ul>
<li>
<!--相当于router-link-->
<nuxt-link to="/">首页</nuxt-link>
</li>
<li>
<nuxt-link to="/about">关于</nuxt-link>
</li>
</ul>
<!--页面路由视图,相当于router-view-->
<nuxt></nuxt>
</div>
</template>
- Custom layout
layouts
Each file (top level) in the directory will create a custom layout that can be accessed through the layout property in the page component.
For example to create a blog layout layouts/blog.vue
:
<template>
<div>
<div>我的博客导航栏在这里</div>
<nuxt />
</div>
</template>
Then you must layout
specify the custom layout referenced by this page in the corresponding page :
<template>
···
</template>
<script>
export default {
layout: 'blog'
}
</script>
- Error page
Nuxt.js
The provisions of layouts
all the files in the root directory of all belong to personalized layout files, in addition to layouts/error.vue
(not need to include <nuxt/>
the label), this file in the layouts
folder, but it is a page for custom error pages (pages 404, 500).
For example, a customized 404
page:
template>
<div class="container">
<h1 v-if="error.statusCode === 404">页面不存在</h1>
<h1 v-else>应用发生错误异常</h1>
<nuxt-link to="/">首 页</nuxt-link>
</div>
</template>
<script>
export default {
props: ['error'],
layout: 'blog' // 为错误页面指定自定义的布局
}
</script>
page
Nuxt.js
The page of is actually Vue
components, and some special configuration items are added on the basis of these components .
<template>
<div>
<h1>{
{
title1 }}</h1>
<ul>
<li v-for="item in list" :key="item.id">
{
{
item.title }}: {
{
item.content }}
</li>
</ul>
</div>
</template>
<script>
export default {
name: "Home",
//Nuxt.js中的钩子函数,专门用于获取页面服务端渲染的数据
async asyncData() {
...
}
};
</script>
data
Nuxt.js
An asyncData method has been added, which can obtain or process data asynchronously before setting the data of the component.
It can only be used in page components, and cannot be used in the
asyncData method of subcomponents of page components . This cannot be used because it is called before the page component is initialized
When to call:
asyncData
Method will be called before the page component is loaded- Called during server rendering and before client routing updates
asyncData
Parameters and return value:
asyncData
The first parameter is set to the context object of the current page (including request / response / params / query / store)Nuxt.js
TheasyncData
returned data and the componentdata
method return data will be fused together for use by the component
Nuxt.js
Several different methods are provided to use the asyncData method:
- Use
async
,await
<template>
...
</template>
<script>
export default {
async asyncData({
params }) {
const {
data } = await axios.get(`https://my-api/posts/${
params.id}`)
return {
title: data.title }
}
}
</script>
- Return one
Promise
, itnuxt.js
will wait for it toPromise
be parsed before setting the data of the component to render the component
<template>
...
</template>
<script>
export default {
asyncData({
params }) {
return axios.get(`https://my-api/posts/${
params.id}`).then(res => {
return {
title: res.data.title }
})
}
}
</script>
Article list
Server-side rendering basic
server-side rendering-Nuxt.js basic
server-side rendering-Nuxt.js comprehensive case
server-side rendering-Nuxt.js comprehensive case release deployment
server-side rendering-Vue SSR construction