当前位置:网站首页>Nuxtjs quick start (nuxt2)

Nuxtjs quick start (nuxt2)

2022-07-06 13:49:00 Ling Xiaoding

nuxtjs Quick start (nuxt2)

Tips : This article is for bloggers to watch b standing up Main front end aka Teachers learn the articles sorted out by video
Video directions :《CMS Full stack project 》 Series nine :Nuxt+ElementUI
nuxtjs Official website (nuxt2):NuxtJS



Preface

Tips : This article is nuxt2:

This article can take you to quickly build a simple Nuxt.js project ,Nuxt.js Is based on Vue.js The general application framework of ,Nuxt.js Preset the use of Vue.js Development Server rendering (SSR) All kinds of configuration required for the application , The article briefly describes Nuxt.js The basic function of , You can get started quickly Nuxt!


Tips : The following is the main body of this article , The following cases can be used for reference

One 、 Quickly generate nuxt project

function create-nuxt-app

 Make sure that... Is installed  npx (npx  stay  NPM  edition  5.2.0  Installed by default ):
npx create-nuxt-app < Project name >
 Or use  yarn :
yarn create nuxt-app < Project name >

 Options


Two 、nuxtjs To configure IP And port

It is often encountered in development that the port is occupied or specified IP The situation of . We need the package.json In the config Item to configure . For example, now we want to IP configure 127.0.0.1 , Port settings 8080.

{
    
    ...,
    "config": {
    
        "nuxt": {
    
          "host": "127.0.0.1",
          "port": "8080"
        }
        // perhaps 
        "nuxt": {
    
          "host": "0.0.0.0",
          "port": "80"
        }
    }
} 

ip modify


3、 ... and 、 stay nuxt Use in less

  1. install less and Specify the version of less-loader
npm install less less-[email protected]7.0.0 --save-dev
  1. Global style file
  • stay static Create... In the directory base.less file , Used to write global styles . Then open the nuxt.config.js And find css
css: [
    'element-ui/lib/theme-chalk/index.css',
        '~/static/base.less'	//  Global styles are added here 
], 
  1. In component styles
<style scoped lang="less">
@bgColor: #f00;
.el-container {
    
  width: 100%;
  height: 100%;

  .el-main {
    
    color: @bgColor;
    height: 100%;
    padding: 0;
  }
}
</style>

Four 、nuxtjs Clear the default style

  1. open reset-css Of npm Website , Take any link :
/* http://meyerweb.com/eric/tools/css/reset/ v5.0.1 | 20191019 License: none (public domain) */

html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, menu, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, main, menu, nav, output, ruby, section, summary, time, mark, audio, video {
    
	margin: 0;
	padding: 0;
	border: 0;
	font-size: 100%;
	font: inherit;
	vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure, footer, header, hgroup, main, menu, nav, section {
    
	display: block;
}
/* HTML5 hidden-attribute fix for newer browsers */
*[hidden] {
    
    display: none;
}
body {
    
	line-height: 1;
}
menu, ol, ul {
    
	list-style: none;
}
blockquote, q {
    
	quotes: none;
}
blockquote:before, blockquote:after, q:before, q:after {
    
	content: '';
	content: none;
}
table {
    
	border-collapse: collapse;
	border-spacing: 0;
}
  1. Paste the code into reset.css, Put it in static Under the table of contents , And in nuxt.config.js introduce :
head: {
    
  ...,
   link: [
     {
     rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' },
     {
     rel: 'stylesheet', type: 'text/css', href: '/reset.css' }	//  introduce 
   ]
 }, 

 Import reset.css
3. Again , You can also put it in the file css In the object , Exist in the form of array items .


5、 ... and 、nuxtjs Use in asyncData Realization SSR

Nuxt Can be in asyncData and created In doing axios request . But in created Make a request in , The rendered data will not appear in html in , Lead to It can't be done SEO Optimize , While using asyncData Make a request , be html Will be rendered , thus Realization SSR. It's not asynchronous
asyncData in Can't get vue Of this, So we have to return,template Can be called directly with curly braces , And use data The data is consistent

//  Page usage asyncData Can achieve SSR Rendering , But the assignment is direct  return {data}
async asyncData() {
    
  let result = await BannerApi();
   if (result.errCode === 0) {
    
     let banner = result.data;
     return {
     banner };
   }
 },
export default {
    
  asyncData({
      params,query }) {
    
    return axios.get(`https://my-api/posts/${
      params.id}`).then(res => {
    
      return {
     title: res.data.title }
    })
  }
}

6、 ... and 、 route

stay page Create a new... In the page vue Components , route Automatic generation Route with the same file name
nuxt route

6.1 Dynamic nested sub route

  1. Can pass vue-router Sub route creation of Nuxt.js Nested routes for applications .
  2. Create an embedded sub route , You need to add one Vue file , At the same time, add a directory with the same name as the file to store the sub view components .
  3. Warning: Don't forget in the parent component (.vue file ) Internal increase <nuxt-child/> Used to display subview content .
     Dynamic nested sub route

7、 ... and 、Nuxt To solve the cross domain

  1. install proxy
npm i @nuxtjs/proxy -D
  1. stay nuxt.config.js Add :
module.exports = {
    
  ...,
  modules: [
    '@nuxtjs/axios',
    '@nuxtjs/proxy'
  ],
  axios: {
    
    proxy: true,
    prefix: '/',
    credentials: true
  },
  proxy: {
    
    '/api/': {
    
      target: 'http://127.0.0.1:9000/web', //  Target server ip
      pathRewrite: {
    
        '^/api/': '/',
        changeOrigin: true
      }
    }
  }
}

  1. axios Of baseURL Use /api that will do

8、 ... and 、Nuxt.js Redirect routing mode

8.1 The way 1

adopt nuxt.config.js Set up , stay nuxt.config.js File add the following configuration .redirect Indicates the redirected route .

router: {
    
    extendRoutes(routes, resolve) {
    
      routes.push({
    
        path: '/',
        redirect: '/film'
      })
    }
  }

8.2 The way 2

Through the middleware file , In the directory middleware Add a name :redirect.js The file of
redirect.js

  1. stay redirect.js Write the following code in , among path and redirect Your route is defined by yourself .
export default function ({
      isHMR, app, store, route, params, error, redirect, }) {
    
  if (isHMR) return; // Used to judge hot updates 
  //  Pages are placed in _lang Under the folder , namely lang Dynamic routing parameters ;
  /* if (!params.lang) { // This writing will cause the problem of too many times of route redirection ; return redirect('/' + defaultLocale + '' + route.fullPath)} */
  if (route.fullPath == "/") {
    
    return redirect("/home");
  }
  if (route.fullPath == '/vue') {
    
    return redirect('/vue/basics')
  }
}

  1. Last but not least nuxt.config.js Add... To the file
router: {
    middleware: 'redirect'}

nuxt.config.js


Nine 、nuxt Use in vue plug-in unit

  1. stay plugins Create one under the directory xxx.js
import Vue from 'vue'
import VueHighlightJS from 'vue-highlightjs' //  tell Vue  To use plug-ins  vue-highlightjs
import 'highlight.js/styles/atom-one-dark.css'

Vue.use(VueHighlightJS)

xxx.js
2. stay nuxt.config.js Middle configuration :

export default {
    
  plugins: ['~/plugins/xxx']
}

nuxt.config.js


summary

Tips : Here is a summary of the article :

for example : That's what I want to talk about today Nuxtjs Content , This article simply introduces Nuxtjs Some uses of , It can let you get started quickly Nuxt, Of course Nuxt There are many powerful functions inside , You can go to the official website and have a detailed look .

原网站

版权声明
本文为[Ling Xiaoding]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060916580581.html