I worked on the NUXT project for a few months and almost lost my job. In the company didn’t open dry nuxt project before, I didn’t contact with nuxt, flow scribble grass see several eyes website to open a dry, in the process also stepped on a lot of pit, also wrote a lot of unnecessary code, so using the touch 🐟 time summarizes some practical use of knowledge, the hope can help you, can make you less shoe pit, if you’re not too good, make do with see.
Middleware Definitions (Nuxt. config, Layout, Pages)
Middleware is the name for middleware and can be used for routing interception, parameter filtering, etc… Middleware can be defined in three ways.
- Nuxt. config Specifies the configuration file definition
export default{
router: {middleware: ['xxxx'] // Write the middleware file name, such as middleware/auth.js, and auth ojbk}}Copy the code
Note ⏰ : middleware defined in nuxt.config should be exported to the js file in the middleware file in the root directory.Copy the code
- Layout Page definition
export default {
middleware:({route,params,query}) = >{
console.log(route,params,query, 'layout')}}Copy the code
- Pages Page definition
export default {
middleware:({route,params,query}) = >{
console.log(route,params,query, 'page')}}Copy the code
The first parameter of Middleware is a context parameter that can deconstruct routes,params, queries, etc… Parameter, enough for us to do all kinds of SAO operations. Since they can be defined in different locations, they can be executed in either front or back 👇.
Execute in nuxt.config => layout => page
Validate parameter (Pages)
The validate hook is used to validate parameters at the page level and deconstructs params, queries… Parameter, and return true indicates that the authentication succeeds, and return false indicates that the authentication fails.
export default {
validate({params,query}){
console.log(params,query,'validate')
return true}}Copy the code
AsyncData Server requests asynchronous data (pages)
AsyncData is mainly used to render server data requests. In its context, it can deconstruct axios, routes,params… To deconstruct axios,route,params… To deconstruct axios,route,params… Parameter, there are some additional configurations that need to be done to deconstruct axios, which you’ll see in the scroll down below. When you deconstruct $Axios, you can make ajax requests and return the data to render.
export default {
async asyncData({$axios,route}){
let data = await $axios('xxx/xxx/xx')
return {
data
}
}
}
Copy the code
Extended routing (nuxt.config)
In nuxt for convention is the default routing, it is in the pages you create a file, or a folder will automatically create the corresponding routing, no manual configuration, is extremely convenient, said there is not much, just said here, when we want to do to an address of a special operation, or a full takeover of stereotypes about routing, You need to use extended routing.
If you want a route called /hahaha/:id to also skip to details, do the same for 👇
export default {
router: {extendRoutes:(routes,resolve) = >{
routes.push({
name:"hahaha".path:'/hahaha/:id'.component:resolve(__dirname,'pages/detail/_id.vue')})}}Copy the code
If you want to take over the full contract routing, you can do so 👇
export default {
router: {extendRoutes(routes, resolve){
return[{name:"home".path:"/".component:resolve(__dirname,'pages/index'),
meta: {title:"home"}}... You can go ahead and write this, but normally if you want to take over a reductic route, you put it in a file and import it [}}}Copy the code
Customize the error page (layout)
Nuxt provides a default error page by default. If you don’t like this error page, you can customize your own error page. You can define an error. There is an error in the error. Vue prop that contains error information
<template> <div> </div> </template> <script> export default {props:[' props ']} </script>Copy the code
Animation customization (CSS, Pages, nuxt.config)
global
If you want to implement a routing animation globally, you can define a global file in the assets/ CSS directory in the root directory (you can always put the global CSS style under assets, or you can put it somewhere in the corner) and implement the following classes 👇
-
page-enter-active
-
page-leave-active
-
page-enter
-
page-leave
🌰
.page-enter-active..page-leave-active{
transition: opacity 1.5 s;
}
.page-enter..page-leave-active{
opacity: 0;
}
Copy the code
Finally, reference this file in nuxt.config to achieve a route switching fade in and out effect.
export default {
css: [
"assets/css/xxx.css"],}Copy the code
local
If you want to have a unique way to enter and exit a routing page, you can also create a unique effect for it. Just give the transition:’ XXXX ‘(XXX is your name, whatever you want) and implement the corresponding class to implement the animation.
-
xxx-enter-active
-
xxx-leave-active
-
xxx-enter
-
xxx-leave
Routing guard
Global guard
-
The middleware defined in Nuxt. config
-
Define the Middleware in Layout
-
Defined in the plugins
Component local guard
- The Middleware defined in the component
Partial rear guard
- Component beforeRouteLeave hook
Data request (nuxt.config)
To make data requests, we need to use Axios, nuXT has integration for us, just install, reference.
-
First step
-
The second step can be introduced in nuxt.config
export default{
modules: [
'@nuxtjs/axios']}Copy the code
Then restart the plugin,aysncData… To the $AXIos parameter
Important note ⏰ : Most of nuxT's integrated libraries will be introduced in Modules.Copy the code
Open the agent
Sometimes our interface is cross-domain, so we need to broker.
-
Step one
-
Step 2 Configure in nuxt.config
-
@nuxtjs/proxy
-
Configure axios and proxy in nuxt.config
export default {
axios: {proxy:true},proxy: {'api/': {target:'http://localhost:3000'}}}Copy the code
Axios intercept
Requesting asynchronous data in normal development requires some interception before and after the request, which is easy to implement in NUXT by defining an Axios interception plugin.
- The first step in
Plugins directory
And give the plugin a sexy name likeaxios.js
export default({$axios})=>{
// Request interception
$axios.onRequest(req= >{
// doing something...
})
// Response intercept
$axios.onResponse(res= >{
// doing something...
})
// Error interception
$axios.onError(err= >{
// doing something...})}Copy the code
- The second step in
nuxt.config
Plugins are introduced in
export default {
plugins: [{src:'~/plugins/axios'.ssr:true AsyncData ({$axios}) intercepts axios requests on both the server (asyncData ({$axios}) and the client (this.$axios). False intercepts only the client}}]Copy the code
Configure loading (nuxt.config)
You can configure loading in two modes. A kind,
- Up-loading style directly in default loading
export default {
loading: {
color: 'blue'.height: '5px'}}Copy the code
It also has this property that you can tune
- Custom loading
export default {
loading: 'Path to a component'
}
Copy the code
The component that’s being pointed to has two special hooks the start hook, the finish hook, what to do when the load starts, and what to do when the load ends
vuex
You can configure vuex to be defined directly in the store directory in the root directory. Note that all vuex files are named except for the index file, which needs to be added when calling, such as (this.store.com MIT (‘ XXX /handle’)).
The format of the VUex file is 👇
export constState => ({})export const getters = {}
export const actions = {}
export const mutations = {}
Copy the code
Configuration UI library
Third-party UI library configuration, using Element-UI as an example.
-
The first step is NPM i-d element-UI
-
The second step is to suggest xxx.js in the plugins directory and then introduce the Element-UI registry
import Vue from 'vue'
import ElementUi from 'element-ui'
Vue.use(ElementUi)
Copy the code
- Step 3 Set the parameters in nuxt.config
Export default {CSS: [" element - the UI/lib/theme. Chalk/index. The CSS "element / / in the UI style], plugins: ['~/plugins/ XXX '// introduce plugin just defined]}Copy the code
Customize meta (nuxt.config,pages)
Customizations can be defined globally in nuxt.config or individually under Pages.
nuxt
export default {
head: {
title: 'test'.meta: [{charset: 'utf-8' },
{ name: 'viewport'.content: 'width=device-width, initial-scale=1' },
{ hid: 'description'.name: 'description'.content: ' '}].link: [{rel: 'icon'.type: 'image/x-icon'.href: '/favicon.ico'}}}]Copy the code
pages
export default {
head:() = >({
title: 'test'.meta: [{charset: 'utf-8' },
{ name: 'viewport'.content: 'width=device-width, initial-scale=1' },
{ hid: 'description'.name: 'description'.content: ' '}].link: [{rel: 'icon'.type: 'image/x-icon'.href: '/favicon.ico'})}}]Copy the code
other
-
Path alias :~ or @srcdir, ~~ or @@rootdir (by default, srcDir and rootDir are the same)
-
Active-class =’ XXX ‘nuxT-link
-
@nuxtjs/style-resources Configure the less, SCSS global variable
-
For more features, see the official website