features
- Based on the Vue. Js
- Automatic code layering
- Server side rendering
- Powerful routing function, support asynchronous data
- Static file service
- ES2015+ syntax support
- Package and compress JS and CSS
- HTML header tag management
- Local development supports hot loading
- Integrated ESLint
- Support for various styles of preprocessors: SASS, LESS, Stylus, and more
- Support for HTTP/2 push
Nuxt rendering process
- The client initiates a request.
- call
nuxtServerInit
Data from the server, such as login information, can be passed to the clientstore
theaction
; - Next call
middleware
Middleware runs functions we define before rendering the page, such as permission control and validation. - then
validate
Verify the parameters carried by the client during execution. asyncData
Obtain data from the server before rendering component, and merge the requested data into data in Vue;render
Page rendering, internal jump<nuxt-link>
Continue the loop.
Nuxt installation
- Run create-nuxt-app to make sure NPX is installed (NPX is installed by default in NPM version 5.2.0) :
NPX create-nuxt-app < project name >
- options
- The directory structure
├─ NuxT - Test ├─ API for Static resource Files in WebPack ├─ Components # Vue components that do not feature asyncData ├─ Layouts page ├─ Middleware # Middleware ├─ pages # directory for.vue files to automatically generate routing configurations. ├── Plugins # Run the Javascript plugin before running the application. ├── State Tree ├─ Nuxt.config.js # Nuxt.js ├ ─ └─ package.json # to override the default configuration for describing app dependencies and exposed script interfacesCopy the code
- Run the project
npm run dev
routing
Routing generation
All *. Vue files in the pages directory automatically generate the application routing configuration.
- Pages /admin.vue Merchandise management page
- Pages /cart.vue Shopping cart page
Nuxt /router.js generates automatic routes
Dynamic routing
A. Vue file or directory is defined as a dynamic route, as follows:
pages/
--| detail/
----| _id.vue
Copy the code
The following route configuration is generated:
{ path: "/detail/:id?" , component:_9c9d895e, name: "detail-id" }Copy the code
The route path contains: ID? Parameter, indicating that the route is optional. If you want to make it a mandatory route, you need to create an index.vue file in the detail directory.
Embedded routines by
To create inline child routing, you need to add a.vue file and a directory with the same name as the file to store the child view components.
The file structure is as follows:
pages/
--| detail/
----| _id.vue
--| detail.vue
Copy the code
The generated route configuration is as follows:
{
path: '/detail',
component: 'pages/detail.vue',
children: [
{path: ':id?', name: "detail-id"}
]
}
Copy the code
Don’t forget to add < nuxt-Child /> to the parent component (.vue file) to display the child view content
view
Configure data and views for the specified route, including application templates, pages, layouts, and HTML headers.
The default layout
- Add routing navigation layouts/default.vue
<div>
<nuxt-link to="/">Home page</nuxt-link>
<nuxt-link to="/admin">management</nuxt-link>
<nuxt-link to="/cart">The shopping cart</nuxt-link>
<nuxt />
</div>
Copy the code
Don’t forget to add a
npm run dev
To view
Custom layout
Create a blank layout page /blank.vue for login.vue
<template>
<div>
<nuxt />
</div>
</template>
Copy the code
Page pages/login.vue uses custom layout:
export default {
layout: 'blank'
}
Copy the code
Custom error pages
Create layouts/error. Vue
<template>
<div>
<h1 v-if="error.statusCode === 404">Page does not exist</h1>
<h1 v-else>Application error exception occurred. Procedure</h1>
<p>{{error}}</p>
<nuxt-link to="/">Home page</nuxt-link>
</div>
</template>
<script>
export default {
props: ['error'].layout:'blank'
}
</script>
<style lang='scss' scoped>
</style>
Copy the code
Test: Visit a page that does not exist
page
Page component is Vue component, stored in pages only nuxt.js for these components to add some special configuration items to the home page add title and meta, the most important one key, support asyncData asynchronous data processing, in addition to the method of the first parameter for the current page component context object.
For example, pages/index.vue, configure header information:
export default {
head(){
return{
title:"Course List".// Vue-meta Uses hid to determine the meta to be updated
meta:[
{name:"description".hid:"description".content:"set page meta"}].link: [{rel:"favicon".href:"favicon.ico"}}}}]Copy the code
Asynchronous data acquisition
The asyncData method allows us to asynchronously fetch or process component data before setting it up.
Example: Get commodity data
Interface to prepare
- Install dependencies
npm i koa koa-router koa-bodyparser -S
- Create a server/index. Js
const Koa = require('koa')
const consola = require('consola')
const { Nuxt, Builder } = require('nuxt')
const app = new Koa()
// Import and Set Nuxt.js options
let config = require('.. /nuxt.config.js') config.dev = ! (app.env ==='production')
async function start() {
// Instantiate nuxt.js
const nuxt = new Nuxt(config)
const {
host = process.env.HOST || '127.0.0.1',
port = process.env.PORT || 3000
} = nuxt.options.server
// Build in development
if (config.dev) {
const builder = new Builder(nuxt)
await builder.build()
} else {
await nuxt.ready()
}
// Listen for all routes
app.use(ctx= > {
ctx.status = 200
ctx.respond = false // Bypass Koa's built-in response handling
ctx.req.ctx = ctx // This might be useful later on, e.g. in nuxtServerInit or with nuxt-stash
nuxt.render(ctx.req, ctx.res)
})
app.listen(port, host)
consola.ready({
message: `Server listening on http://${host}:${port}`.badge: true
})
}
start()
Copy the code
- Creating an interface file
// This file is not nuxT generated and provides the data service interface for the demo project
const Koa = require('koa');
const app = new Koa();
const bodyparser = require("koa-bodyparser");
const router = require("koa-router") ({prefix: "/api" });
// Set the cookie encryption key
app.keys = ["some secret"."another secret"];
const goods = [
{ id: 1.text: "Clothes".price: 60 },
{ id: 2.text: "Shoes".price: 200}];// Configure the route
// Get the product list
// http://localhost:8080/api/goods
router.get("/goods".ctx= > {
ctx.body = {
ok: 1,
goods
};
});
// Product details
router.get("/detail".ctx= > {
ctx.body = {
ok: 1.data: goods.find(good= > good.id == ctx.query.id)
};
});
/ / login
router.post("/login".ctx= > {
const user = ctx.request.body;
if (user.username === "jerry" && user.password === "123") {
// Save the token to the cookie
const token = 'a mock token';
ctx.cookies.set('token', token);
ctx.body = { ok: 1, token };
} else {
ctx.body = { ok: 0}; }});// Parse the POST data and register the route
app.use(bodyparser());
// Register the route
app.use(router.routes());
app.listen(8080.() = > console.log('API service started'))
Copy the code
Integrated axios
- Install @nuxt/axios module:
npm install @nuxtjs/axios -S
- Configuration: nuxt. Config. Js
modules: [
'@nuxtjs/axios'].// Configure cross-domain, not required if nginx is configured
axios: {proxy:true
},
proxy: {"/api":"http://localhost:8080"
},
Copy the code
Test code: get commodity list pages/index.vue
export default {
// Since the asyncData method is called before the component is initialized, there is no way to refer to the component instance object through this within the method.
// $axios is injected by the nuxtjs/axios module
// $get is a fetch style API wrapped by the AXIos module
async asyncData({$axios,error}){
const {ok,goods} = await $axios.$get("api/goods");
if(ok){
return {goods}
}
error({statusCode:400.message:"Data query failed"}}})Copy the code
The middleware
Middleware runs functions we define before a page or group of pages are rendered, often for permission control, validation, and so on. Example code: Admin page protection, create Middleware /auth.js
// Define middleware with the context object provided by NUxT
export default function({route,redirect,store}){
// Access the global state of vUX in the context of store
// Check whether the user logs in by checking whether the token exists in VUX
if(! store.state.user.token){ redirect("/login? redirect="+route.path); }}Copy the code
Register middleware, Pages /admin.vue
<script>
export default {
middleware: ['auth']
}
</script>
Copy the code
Global registration: will apply to all pages, nuxt.config.js
router: {
middleware: ['auth']}Copy the code
State management VUEX
If there is a Store directory in the application root directory, nuxt. js will enable the vuex state tree. When defining each state tree, you can export state, mutations, getters, actions. State is exported as a function and the rest as objects.
Example code: user login and login state save, create store/user.js
export const state = () = > ({
token:' '
});
export const mutations = {
init(state,token){ state.token = token; }};export const getters = {
isLogin(state){
/ /!!!!! This is equivalent to converting state.token directly to Boolean
return!!!!! state.token } };export const actions = {
login({commit,getters},u){
$axios is provided by the @nuxt/axios module
return this.$axios.$post("api/login",u).then(({token}) = > {
if(token){
commit("init",token)
}
returngetters.isLogin; }}})Copy the code
Log-in page logic Pages /login.vue
<template>
<div>
<h2>The user login</h2>
<input v-model="user.username">
<input type="password" v-model="user.password">
<button @click="onLogin">The login</button>
</div>
</template>
<script>
export default {
layout:'blank'.data(){
return{
user: {username:"".password:""}}},methods: {onLogin(){
this.$store.dispatch("user/login".this.user).then(ok= > {
if(ok){
console.log(this.$route.query.redirect)
const redirect = this.$route.query.redirect || '/';
this.$router.push(redirect); }})}}}</script>
<style lang='scss' scoped>
</style>
Copy the code
The plug-in
Nuxt.js executes plug-in functions before running the application, which is especially useful when you need to introduce or set up Vue plug-ins, custom modules, and third-party modules.
Example code: Add request interceptor additional token, create plugins/interceptor.js
export default function({$axios,store}){
$axios.onRequest(config= > {
if(store.state.user.token){
config.headers.Authorization = "Bearer " + store.state.user.token;
}
returnconfig; })}Copy the code
Register the plug-in, nuxt.config.js
plugins: ["@/plugins/interceptor"]
Copy the code
nuxtServerInit
By defining the nuxtServerInit method in the root module of the Store, nuxt.js calls it with the page context object as the second argument. This is useful when we want to transfer some data from the server to the client.
Example code: initialize login status, get token store/index.js from server cookie
export const actions = {
nuxtServerInit({commit},{app}){
const token = app.$cookies.get("token");
if(token){
console.log("nuxtServerInit:token:"+token);
commit("user/init",token)
}
}
}
Copy the code
- Install the dependency module: cookie-universal-nuxt
npm i cookie-universal-nuxt -S
The configuration, nuxt. Config. Js
modules:["cookie-universal-nuxt]
- NuxtServerInit can only be written in store/index.js
- NuxtServerInit is executed only on the server side
Release deployment
- Server-side rendering application deployment:
Build first, then start the NUXT service
npm run build
npm start
Copy the code
The generated content is in.nuxt/dist
- Static Application Deployment
Nuxt.js can be static based on the routing configuration, allowing us to deploy the application to any static site hosting service.
npm run generate
Note that both the render and interface servers need to be started
Generate content in dist