Configuration Nuxt
Install Nuxt
Just use the website to go to Quickstart
NPX create-nuxt-app < project name >Copy the code
Configuration stylus
The installation package
npm i -S stylus stylus-loader
Copy the code
configuration
No need to configure, import directly in JS, then create styl pages in the js directory
<template>
<div></div
</template>
<style scoped lang="stylus" src="./style.styl"></style>
Copy the code
Configure an adaptive VW layout
The installation package
npm install postcss-px-to-viewport -D
Copy the code
or
yarn add postcss-px-to-viewport -D
Copy the code
configuration
In fact, the configuration content of this piece is no different from vUE, mainly in nuxT configuration items, through the form of nuxT plug-in
Find build in nuxt.config.js
ViewportWidth here is based on the design draft, mobile terminal is generally 6s 375 width based
Build: {transpile: [/^element-ui/], // Install element UI postcss: {plugins: [require('postcss-px-to-viewport')({
unitToConvert: "px", // The unit to be converted. Default is"px"ViewportWidth: 1920, // The width of the window corresponds to the width of the PC design draft, generally 1920 // viewportHeight: 1080,// the height of the window corresponds to the height of our design draft unitPrecision: PropList: [// attributes that can be converted to VW"*"
],
viewportUnit: "vw"// The desired viewport unit fontViewportUnit:"vw", // The viewport unit used by the font selectorBlackList: [], // The CSS selector that needs to be ignored will not be converted to viewport unit, and the original px unit will be used. MinPixelValue: 1, // Set the minimum conversion value, if 1, only values greater than 1 will be converted mediaQuery:false// Whether the unit in the media query needs to be convertedtrue. / / whether change directly attribute values, but not exclude: add spare attribute/(\ | \ \) (node_modules) (\ | \ \) /, / / ignore certain file folder or a particular file, for example'node_modules'Under file})]}}Copy the code
Configure in VUE
See this article for configuration in VUE
Configure an adaptive VW layout in VUE-CLI4 from scratch
The resources
Nuxt. Js introduced postcss – px – to – the viewport
| configuration vuex way a conventional way
Create index.js file in 1-1. store
1-2. Build store content in index.js
import Vue from 'vue'
import Vuex from 'vuex'
import createLogger from 'vuex/dist/logger'Vue.use(Vuex) const debug = process.env.NODE_ENV ! = ='production'
export const state = () => ({
barIndex: '1'
})
export const getters = {
barIndex: state => state.barIndex
}
export const mutations = {
CHANGE_INDEX (state, value) {
state.barIndex = value
window.sessionStorage.setItem('barIndex', value)
}
}
export const strict = debug
exportconst plugins = debug ? [createLogger()] : [] // Classic(not recommended) : store/index.js Returns the method to create an instance of vuex.store. // const store = new Vuex.Store({ // state: { // barIndex:'1'
// },
// getters: {
// barIndex: state => state.barIndex
// },
// mutations: {
// CHANGE_INDEX (state, value) {
// state.barIndex = value
// window.sessionStorage.setItem('barIndex', value)
// }
// },
// strict: debug,
// plugins: debug ? [createLogger()] : []
// })
// export default () => store
Copy the code
2 | modular configuration vuex way
2-1. Directory structure
2-2. Status content
2-2-1. index
Initialize store to specify the files corresponding to different vuex states
import Vue from "vue";
import Vuex from "vuex";
import * as actions from "./actions";
import * as getters from "./getters";
import state from "./state";
import mutations from "./mutations";
import createLogger from "vuex/dist/logger"; Vue.use(Vuex); // Set the log to be printed only in the development environment const debug = process.env.node_env! = ="production";
export default new Vuex.Store({
actions,
getters,
state,
mutations,
strict: debug,
plugins: debug ? [createLogger()] : []
});
Copy the code
2-2-2. state
Website to explain
const state = {
status: ""};export default state;
Copy the code
2-2-3. getters
Website to explain
It is easier to call properties in state
export const status = state => state.status;
Copy the code
The helper function mapGetters is used to get the data defined in state, which can be used directly through this.status
Computed: {// Mix getters into a computed object using the object expansion operator... mapGetters(['status',
// ...
])
}
Copy the code
2-2-4. mutation-types
Website to explain
export const SET_STATUS = "SET_STATUS";
Copy the code
2-2-5. mutations
Website to explain
import * as types from "./mutation-types"; Open mutations = {[types.SET_STATUS](state, payload) { state.status = payload; }};export default mutations;
Copy the code
It is generally used using the auxiliary function mapMutations
Methods: {// introduce... mapMutations({ set_status:'SET_STATUS'}), // use this.set_status('number1')}Copy the code
2-2-5. actions
Website to explain
import * as types from "./mutation-types";
exportConst actionsSetdataInfo = ({commit}, data) => { Sync data into mutations commit(types.SET_STATUS, data); };Copy the code
Configuring a Default Template
Vue has an app.vue, which can write layout
Nuxt includes a customized layout directory
I wrote that I need to import the common component nav-bar at the beginning of each component
All we need to do is import the public components we wrote earlier in defalult.vue
<template>
<div>
<nav-bar />
<nuxt />
</div>
</template>
<script>
import navBar from '.. /components/nav_bar'
export default {
components: {
navBar
}
}
</script>
Copy the code
So you have a common navigation layout
Configure the AXIOS proxy interface
The nuxt.config page is displayed
axios: {
// baseURL: 'https://www.abc.cn',
prefix: '/api'// Add a prefix to the URL'/api'
credentials: true// Whether to use credential proxy for cross-domain requests:true// enable proxy}, proxy: {'/api': {
target: 'https://www.abc.cn/api'// Since my interface starts with/API, I will add API pathRewrite: {'^/api': '/'// Replace/API with'/'The best request address becomes https://www.abc.cn/api changeOrigin:true// Whether to cross domain}}},Copy the code
Configure the AXIos interceptor
The premise is that the installation plugin Axios must be selected when scaffolding nuXT
1. Nuxt. Config configuration
Configure AXIOS in plugins
plugins: [
'@/plugins/element-ui'.'@/plugins/axios'].Copy the code
Add axios.js to your plugins folder
export default function ({ $axios, redirect}, inject) {) // Request callback //$axios.onRequest((config) => {
// console.log('Making request to '+ config.url) //}) // Request a callback$axios.interceptors.request.use(
(config) => {
// do something before request is sent
return config
},
(error) => {
// do something with request error
returnPromise.reject(error)} // Return a callback$axios.interceptors.response.use((response) => {
if (response.data.success === false) {
console.log('Request failed')
return
}
console.log(response)
return response
}, (err) => {
// if (err && err.response) {
// switch (err.response.status) {
// case 400: err.message = 'Request error (400)'; break
// case 401: return history.push('/login') / /case 403: err.message = 'Access denied (403)'; break
// case 404: err.message = 'Request error (404)'; break
// case 408: err.message = 'Request timed out (408)'; break
// case 500: err.message = 'Server error (500)'; break
// case 501: err.message = 'Service Not realized (501)'; break
// case 502: err.message = 'Network Error (502)'; break
// case 503: err.message = 'Service unavailable (503)'; break
// case 504: err.message = 'Network Timeout (504)'; break
// case 505: err.message = 'HTTP version not supported (505)'; break// default: err.message = 'Connection error (${err.response.status})! '//} //else {
// err.message = 'Failed to connect to server! '
// }
// message.error(err.message)
returnPromise.reject(err)}) // Error callback$axios.onError((e) => {
const code = parseInt(e.response && e.response.status)
console.log('bug', code)
switch (code) {
case 400:
redirect('/error')
// error({ statusCode: 400, message: 'not found' })
break
case 600:
redirect({
path: '/error'
})
// error({ statusCode: 600, message: 'User not authenticated' })
break
// case 401: return history.push('/login'); break;
// case 403: err.message = 'Access denied (403)'; break;
// case 404: err.message = 'Request error (404)'; break;
// case 408: err.message = 'Request timed out (408)'; break;
// case 500: err.message = 'Server error (500)'; break;
// case 501: err.message = 'Service Not realized (501)'; break;
// case 502: err.message = 'Network Error (502)'; break;
// case 503: err.message = 'Service unavailable (503)'; break;
// case 504: err.message = 'Network Timeout (504)'; break;
// case 505: err.message = 'HTTP version not supported (505)'; break; // default: err.message = 'Connection error (${err.response.status})! `; }})}Copy the code
There is a problem, however, with server access there is no way to use the Element component in AxiOS… Trying to solve
3. Add error. Vue to your layouts
When a server enters the page and reports an error, the server will see the default layouts
<template>
<div class="container">
<nuxt-link to="/">
Home page
</nuxt-link>
</div>
</template>
<script>
export default {
props: ['error'],
layout: 'blog'
}
</script>
Copy the code
4. Add error.vue to the Pages folder
If an error occurs on the pages page, the error page is displayed on the Pages page
<template>
<div class="container">
<nuxt-link to="/">
Home page
</nuxt-link>
</div>
</template>
<script>
export default {
props: ['error'],
layout: 'blog'
}
</script>
Copy the code
5. Use asyncData in the page to fetch data
async asyncData ({ $axios }) {
const aRes = {}
const res = await $axios.$post('/yourAPi', aRes)
console.log(res)
}
Copy the code
The resources
Nuxt.js actual combat and configuration
Nuxt climb pit
Nuxt life cycle
export default {
middleware() {}, // servervalidate() {}, // serverasyncData() {}, // both server and client executefetch() {}, // store data loadingbeforeCreate() {// both server and client execute},created() {// both server and client execute},beforeMount() {}, // clientmounted() {} // client}Copy the code
Deploy Nuxt online
Deployment to the online problem is really bald
Packaging project
npm run build
Copy the code
Publish the project
Configuring node Ports
Configure in package.json with a config property parallel to name
Either 0.0.0.0 or 127.0.0.1 represents the local IP address of the server
"name": "project_ssr"."version": "1.0.0"."description": "My ultimate Nuxt.js project"."author": "mikoMa"."private": true."config": {
"nuxt": {
"host": "0.0.0.0"."port": "3333"}},Copy the code
Publish to the server
The local file. Nuxt, static, package. Json, package – lock. Json, nuxt. Config. Js, these a few a folder or file on the server directory
I put it in the root directory, my new web_SSR folder
Subcontracting in service
You need to deploy the Node environment, as you can see in my other article
Execute commands in the web_SSR folder
npm install
Copy the code
Start the Node service using pM2
Install PM2, you can see my other article
Execute listening command
pm2 start npm --name "project_ssr" -- run start --watch
Copy the code
- Note: Name here corresponds to the project name in package.json
As is shown in
MAC system. Nuxt not found
If you want to hide a file of this type after publishing it, change the last value to True to false
defaults write com.apple.finder AppleShowAllFiles -bool true
Copy the code
Configure nginx
Nuxt official website has various distribution methods, because the use of nginx release, so use nginx official change, do not use vue version, it is useless
Official documentation – Nginx proxy
server {
listen 2222; Configure the security group on the cloud platform. At the same time, the firewall should be turned on
server_name localhost; # If it is a domain name, then the domain name, I here is the IP address access
# Because the client is not configured with compression, this is commented out
#gzip on;
#gzip_types text/plain application/xml text/css application/javascript;
#gzip_min_length 1000;
location / {
expires off;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_read_timeout 1m;
proxy_connect_timeout 1m;
proxy_pass http://127.0.0.1:3333; The default port is 3000, because there is still a service on the server, so I changed the port}}Copy the code
Restart nginx after configuration
nginx -s reload
nginx -s reopen
Copy the code
Visit page appears 500,404,
There is usually a configuration problem, there is no need to prevent 404 in vUE, and there is no need to configure image caching