Nuxt. Introduction to js
1. Nuxt. Js is what
In short, nuxt.js can statically implement vue projects so that they can be better deployed, while making some SEO optimizations (from SPA to multiple static HTML pages).
2. Download and initialize the installation
You need to download vuE-CLI first
npm install vue-cli -g
Copy the code
You can use vue -v to view the version of VUE-CLI
You can then initialize the project with the scaffolding tool:
NPX create-nuxt-app < project name >Copy the code
You need to make the following choices: ① integrated server framework ② UI framework ③ testing framework ④Nuxt mode, etc., just choose what you want
The project can then be opened by NPM run dev, which defaults to port 3000
3. Directory structure
Static is a file that contains static resources, such as img or Sass. These files are not processed by nuxt.js calling Webpack. When the server starts, files in this directory are mapped to the root/of the application.
For example: /static/robots.txt maps to /robots.txt
Components obviously holds components
Plugins are plugins. For example, I selected Element as the UI in the previous configuration, so there will be an element-ui.js
Store is about the vuex Store file, it can be removed if it is not needed
Pages is the most important section, organizing the application’s routes and views. The nuxt.js framework reads all.vue files in this directory and automatically generates the corresponding routing configuration.
This demonstrates an important advantage of nuxt.js: automatic routing configuration
You can also configure assets, layouts, and Middleware
The alias
The alias | directory |
---|---|
~ 或 @ |
srcDir |
~ ~ 或 @ @ |
rootDir |
By default, srcDir is the same as rootDir.
Tip: In the vue template, to import assets or static directory, use ~/assets/your_image. PNG and ~/static/your_image. PNG.
4. Configuration file
A lot of configuration can be done in nuxt.config.js
For example, configure the HEAD content of HTML
Specific configuration can be in www.nuxtjs.cn/guide/confi…
In addition to normal configuration items, you can also configure CSS content such as page loading loading bar, route switching animation, etc
The name of the | role |
---|---|
build | Nuxt.js allows you to automatically generatevendor.bundle.js Add modules to the file to reduce the size of the application bundle. This configuration item is useful if your application relies on third-party modules. |
css | This configuration item is used to define the application’s global (all pages need to reference) style file, module, or third-party library. |
dev | This configuration item is used to configure whether the nuxt.js application is in development mode or production mode. |
env | This configuration item defines the application client and server environment variables. |
generate | This configuration item defines the parameters of each dynamic route. Nuxt.js generates static files corresponding to the directory structure based on these route configurations. |
head | This configuration item configures the default meta tag of an application. |
loading | This configuration item is used to customize the load component used by nuxt.js. |
modules | This configuration item allows you to add Nuxt modules to your project. |
modulesDir | This configuration item allows you to defineNuxt.js application-specificnode_modules Folder. |
plugins | This configuration item is used to configure those required in theRoot vue. Js applications Instantiate the Javascript plug-in you need to run before. |
rootDir | This configuration item is used to configure the root directory of the nuxt.js application. |
router | This configuration item can be used to override the nuxt.js defaultvue-router configuration |
server | This option allows you to configure server instance variables for your nuxt.js application. |
srcDir | This configuration item configures the source directory path of the application. |
dir | This option allows you to configure a custom directory for your nuxt.js application. |
transition | This configuration item is used to personalize the default value of the application transition properties. |
Detailed configuration file usage will be covered later
5. The routing
An intuitive benefit of nuxt.js is that it automatically configures vue-Router, just by writing vue files to the Pages folder as per convention.
For example, here is the document structure:
We can find index.html, blog.html and one/two.html
To switch routes on a page, use nuxt-link instead of router-link
<nuxt-link to="/one/two">Jump to one/two HTML</nuxt-link>
Copy the code
Dynamic routing
Many times we need dynamic routes to display specific content (for example, every blog post, every news item, every product, etc.)
It is also very easy to configure dynamic routing in nuxt.js, requiring only the specific name: _ Dynamic routing parameter (i.e., XXX of $route.params.xxx).vue, the key is to start with an underscore, such as id.vue
You can also use the re to verify parameters
validate({params}) {
return /^\d+$/.test(params.id);
// Check that the parameters are full digits, successful and normal, failed to enter 404.html
}
Copy the code
Route Animation
Create a new main. CSS under Assets /. Here is the default animation on the official website
.page-enter-active..page-leave-active {
transition: opacity 0.5 s;
}
.page-enter..page-leave-active {
opacity: 0;
}
Copy the code
It can be seen that the animation switch starts with. Page, enters as. Page-enter-active, and leaves as. Page-leave-active
Then introduce CSS in nuxt.config.js:
Note: Only the nuxT-link tag can trigger the animation effect. If the A tag is used, it cannot be achieved. It is recommended to follow the convention
6. Default template and default layout
To customize the default HTML template, simply create an app.html file in the SRC folder (the app root by default). The default template is:
<! DOCTYPEhtml>
<html {{ HTML_ATTRS}} >
<head {{ HEAD_ATTRS}} >
{{ HEAD }}
</head>
<body {{ BODY_ATTRS}} >
{{ APP }}
</body>
</html>
Copy the code
{{HEAD}} introduces the meta tag configured in nxut.config.js, and {{APP}} is the specific template for each page
So to add something consistent to each page, just put it in the body:
<! DOCTYPEhtml>
<html {{ HTML_ATTRS}} >
<head {{ HEAD_ATTRS}} >
{{ HEAD }}
</head>
<body {{ BODY_ATTRS}} >
<a href='www.baidu.com'>baidu</a>
{{ APP }}
</body>
</html>
Copy the code
Note: The service needs to be restarted to take effect
In fact, the same functionality can be implemented in the default layout because it is a change in template (the default layout cannot customize anything other than the body)
You can expand your application’s default layout by adding a layouts/default.vue file.
Tip: Don’t forget to add a
component to the layout file to display the body of the page.
<template>
<a href='www.baidu.com'>baidu</a>
<nuxt />
</template>
Copy the code
So changes in the page are usually added to the default layout, and the default template is mainly added to the compatibility policy:
<! DOCTYPEhtml>
<! --[if IE 9]><html lang="en-US" class="lt-ie9 ie9" {{ HTML_ATTRS }}><! [endif]-->
<! --[if (gt IE 9)|!(IE)]><! --><html {{ HTML_ATTRS}} ><! - <! [endif]-->
<head {{ HEAD_ATTRS}} >
{{ HEAD }}
</head>
<body {{ BODY_ATTRS}} >
{{ APP }}
</body>
</html>
Copy the code
If you want to customize an error page (for example, 404,500), write it in layouts/error.vue, which is treated as a real page rather than a layout.
<template>
<div class="container">
<h1 v-if="error.statusCode === 404">Page does not exist</h1>
<h1 v-else>Application error exception occurred. Procedure</h1>
<nuxt-link to="/">The first page</nuxt-link>
</div>
</template>
<script>
export default {
props: ['error'].layout: 'blog' // You can specify a custom layout for error pages
}
</script>
Copy the code
7. The head custom
In SEO optimization, the most important part is to configure meta tags according to the content of the page. However, in the previous article, the title and content of the meta are written in nuxt.config.js, which is obviously not right
Nuxt.js provides a way to customize head: just add the head method to page.vue:
The data in data is rendered to the page using interpolation expressions. The head method uses this to fetch the data in data, and the meta can be used to configure the tag directly, instead of using this.data
<template>
<h1>{{ title }}</h1>
</template>
<script>
export default {
data() {
return {
title: 'Hello World! '}},head() {
return {
title: this.title,
meta: [{hid: 'description'.name: 'description'.content: 'My custom description'}]}}}</script>
Copy the code
8. Asynchronous data
-
Create a data warehouse (an address where you can get json files)
-
Create asyncData. Vue
- Get the data using AXIos
- Get data using the asyncData method (you can use the async await syntax sugar)
async asyncData({ params }) { const { data } = await axios.get(`https://my-api/posts/${params.id}`) return { res: data.title } } Copy the code
The value of the return automatically creates a variable in the data. In this example, we created a res, which can be accessed by this.res, eliminating the need to bind data to a variable in the data
Note: The asyncData method is actually called before the component is initialized, so this is not used to access the data, but the data is bound automatically
9. Resource files
It’s recommended to use a graph bed for all of this, but it’s worth understanding the nuxt.js directory structure here
You can use an alias to access a folder such as assets to easily obtain the relative path of the file, such as ~assets/img/logo.png
The same goes for background images in CSS
You can use live-serve to test the server, but you can also use static pages like Gitee Pages directly