当前位置:网站首页>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
List of articles
- nuxtjs Quick start (nuxt2)
- Preface
- One 、 Quickly generate nuxt project
- Two 、nuxtjs To configure IP And port
- 3、 ... and 、 stay nuxt Use in less
- Four 、nuxtjs Clear the default style
- 5、 ... and 、nuxtjs Use in asyncData Realization SSR
- 6、 ... and 、 route
- 7、 ... and 、Nuxt To solve the cross domain
- 8、 ... and 、Nuxt.js Redirect routing mode
- Nine 、nuxt Use in vue plug-in unit
- summary
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 >

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"
}
}
}

3、 ... and 、 stay nuxt Use in less
- install
lessand Specify the version ofless-loader
npm install less less-[email protected]7.0.0 --save-dev
- Global style file
- stay
staticCreate... In the directorybase.lessfile , Used to write global styles . Then open thenuxt.config.jsAnd findcss:
css: [
'element-ui/lib/theme-chalk/index.css',
'~/static/base.less' // Global styles are added here
],
- 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
- open reset-css Of
npmWebsite , 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;
}
- Paste the code into
reset.css, Put it instaticUnder the table of contents , And innuxt.config.jsintroduce :
head: {
...,
link: [
{
rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' },
{
rel: 'stylesheet', type: 'text/css', href: '/reset.css' } // introduce
]
},

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 
6.1 Dynamic nested sub route
- Can pass
vue-routerSub route creation ofNuxt.jsNested routes for applications . - Create an embedded sub route , You need to add one
Vuefile , At the same time, add a directory with the same name as the file to store the sub view components . - Warning: Don't forget in the parent component (.vue file ) Internal increase
<nuxt-child/>Used to display subview content .
7、 ... and 、Nuxt To solve the cross domain
- install
proxy
npm i @nuxtjs/proxy -D
- stay
nuxt.config.jsAdd :
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
}
}
}
}
axiosOfbaseURLUse/apithat 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 
- stay
redirect.jsWrite the following code in , amongpathandredirectYour 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')
}
}
- Last but not least
nuxt.config.jsAdd... To the file
router: {
middleware: 'redirect'}

Nine 、nuxt Use in vue plug-in unit
- stay
pluginsCreate one under the directoryxxx.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)

2. stay nuxt.config.js Middle configuration :
export default {
plugins: ['~/plugins/xxx']
}

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 .
边栏推荐
- Detailed explanation of redis' distributed lock principle
- Implementation principle of automatic capacity expansion mechanism of ArrayList
- 4.二分查找
- C语言入门指南
- 4. Binary search
- The latest tank battle 2022 - Notes on the whole development -2
- Leetcode.3 无重复字符的最长子串——超过100%的解法
- 2022 Teddy cup data mining challenge question C idea and post game summary
- canvas基础2 - arc - 画弧线
- Aurora system model of learning database
猜你喜欢
![[during the interview] - how can I explain the mechanism of TCP to achieve reliable transmission](/img/d6/109042b77de2f3cfbf866b24e89a45.png)
[during the interview] - how can I explain the mechanism of TCP to achieve reliable transmission

Programme de jeu de cartes - confrontation homme - machine

自定义RPC项目——常见问题及详解(注册中心)

FAQs and answers to the imitation Niuke technology blog project (II)

A piece of music composed by buzzer (Chengdu)

Pit avoidance Guide: Thirteen characteristics of garbage NFT project

2. Preliminary exercises of C language (2)

Leetcode. 3. Longest substring without repeated characters - more than 100% solution

SRC挖掘思路及方法

6. Function recursion
随机推荐
7-3 构造散列表(PTA程序设计)
【黑马早报】上海市监局回应钟薛高烧不化;麦趣尔承认两批次纯牛奶不合格;微信内测一个手机可注册俩号;度小满回应存款变理财产品...
1.C语言初阶练习题(1)
【九阳神功】2022复旦大学应用统计真题+解析
仿牛客技术博客项目常见问题及解答(二)
杂谈0516
20220211-CTF-MISC-006-pure_ Color (use of stegsolve tool) -007 Aesop_ Secret (AES decryption)
记一次猫舍由外到内的渗透撞库操作提取-flag
Aurora system model of learning database
Programme de jeu de cartes - confrontation homme - machine
SRC挖掘思路及方法
Miscellaneous talk on May 14
C language to achieve mine sweeping game (full version)
3.猜数字游戏
2022 Teddy cup data mining challenge question C idea and post game summary
The latest tank battle 2022 - Notes on the whole development -2
The latest tank battle 2022 - full development notes-3
[面試時]——我如何講清楚TCP實現可靠傳輸的機制
MySQL中count(*)的实现方式
抽象类和接口的区别