preface
In the process of nuxt development, some pits were encountered. Through official documents and Baidu oriented learning, these pits were solved. Finally, the solutions of these pits were recorded. There is no need to read the full text, just read the required content directly. "Nuxt related pits will be updated in the future, and correction is welcome"
Style classification
When the page structure is complex enough, all the codes of template, srcitp and style are written in vue files are redundant and inconvenient to view when the code is needed. You can separate the style code and store it in a separate style file (such as:. css,. scss). The style file of this article is scss, and other style files are the same.
Basic structure ├─ assets - Asset catalog │ └─ scss - Style assets.scss │ │ ├─ page - Page style file directory │ │ │ ├─ ....scss - Other style files │ │ │ └─ index.scss - Home page style file │ │ │ var.scss - Public variable「Create on demand」 │ │ └─ styles.scss - Main entry of style file to be extracted └─ pages - page directory ├─ ....vue - Other page files └─ index.vue - home page
// styles.scss // Public variables need to be declared in advance: $theme-color: #096; // Direct definition; @import "pages/var.scss"; // Or use files to store public variables separately. // Import all the style files in the page style directory @import "pages/....scss"; @import "pages/index.scss";
// nuxt.config.js export default { // Add the following configuration to automatically reference styles when the project is running or packaged SCSS file css: [ { src: '~/assets/scss/styles.scss' } ] }
api request
axios
normal Use create nuxt app Initialize the project and add axios directly.
# Install axios npm install @nuxtjs/axios --save
// nuxt.config.js export default { // Add the following configuration modules: [ // https://go.nuxtjs.dev/axios '@nuxtjs/axios', ], }
By completing the above steps, you can use axios requests in your project.
// Request in the created lifecycle function created() { this.$axios.get('/Interface address') .then(res => { console.log(res) }) .catch(e => { console.log(e) }) }
Cross domain, proxy
When axios requests, a cross domain problem occurs. It needs to be solved through agents.
The steps are mainly divided into installation and configuration.
# Install proxy npm install @nuxtjs/proxy --save
export default { // Add the following configuration axios: { proxy: true, // Indicates that the agent is turned on prefix: '/api', // Prefix the request url / API - > local debugging http://localhost:3000/api/ credentials: true // Indicates whether credentials are required for cross domain requests }, proxy: { '/api': { target: 'http://www.request. Cn / API ', / / target interface domain name - > Project packaging http://www.request.cn/api changeOrigin: true, // Indicates whether to cross domain pathRewrite: { '^/api': '' // Replace / api with '' when packaging } } }, }
SEO
Search engine optimization (SEO)
Search engine optimization is divided into off-site SEO and on-site SEO. The main work of SEO is to understand how all kinds of search engines crawl internet Page, how to index and how to determine its ranking of search results for a specific keyword technology , to optimize the web page to improve the search engine ranking, so as to improve the website traffic, and finally improve the website's sales ability or publicity ability.
For the front end, seo optimization mainly includes title tag, meta tag, etc. (commonly known as: tdk).
<title>Website title</title> <meta name="description" content="Website description" /> <meta name="keywords" content="Website keywords" /> <img alt="Problems displayed when pictures cannot be loaded" title="The text displayed when the mouse hovers over the picture"> <!-- Can also be seo Relevant reptiles captured -->
Data dynamic setting
In the nuxt project, you can config. JS to configure global static tdk data. You can also use the nuxt built-in method head() to set local static tdk data in the pages directory page.
More static head configurations: nuxtjs meta-tags-seo
When changing, you need to find the corresponding code file to change, which is not conducive to later maintenance, so it is generally dynamically set through API request + head().
// Dynamic setting is required vue page file <template> ... </template> <script> export default { // 1. Data acquisition // asyncData cannot use this (current component) // Provide the first parameter context, which represents the context (all functions of nuxt) // Or deconstruct the context object, context$ axios —> { $axios } async asyncData({ $axios }) { return await $axios .$post(`The requested interface is required`, { [Parameter name]: 'value' }) .then((res) => { const { msg } = res return { title: msg.title, description: msg.description, keywords: msg.keywords, } }) .catch((err) => { throw new Error(err) }) }, // 2. Data setting head() { return { title: this.title, meta: [ { hid: 'description', name: 'description', content: this.description }, { hid: 'keywords', name: 'keywords', content: this.keywords }, ] } } } </script> <style> ... </style>
connect ECONNREFUSED
Scenario reproduction: if the page does not use the async asyncData method to request the background address, it can request normally. If this method is used to request the background address, the following exception will be reported.
// Abnormal information connect ECONNREFUSED 127.0.0.1:80 at TCPConnectWrap.afterConnect [as oncomplete]
Solution 1:
// nuxt.config.js export default { // Add the following configuration server: { port: 80, host: '0.0.0.0' }, }
Solution 2:
// package.json { // Add the following configuration "config": { "nuxt": { "host": "0.0.0.0", "port": "80" } } }
More description of connect econnreused exceptions: Exception resolution - big orange Hi
Pack Project
When the nuxt project is packaged and run, the css part style and nuxt request method will be packaged in html, which is not conducive to source code viewing and SEO ranking.
css internal style:
window.__NUXT___ Anonymous method:
css automatically creates files and references them
// nuxt.config.js file export default { build: { extractCSS: { allChunks: true }, // This configuration can be repackaged and added again } }
js automatically creates files and references them
Method 1: modify Vue renderer JS file
// node_modules/@nuxt/vue-renderer/dist/vue-renderer.js APP += `<script>${serializedSession}</script>` // Comment this statement and repackage it
Method 2: nuxt config. JS add configuration item
// Add the hooks configuration item and repack it hooks: { 'vue-renderer:ssr:context'(context) { const routePath = JSON.stringify(context.nuxt.routePath) context.nuxt = { serverRendered: true, routePath } } },
More nuxt related packages: Nuxt removes css and window from the source code__ NUXT__ - CV mage