当前位置:网站首页>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 .
边栏推荐
- A piece of music composed by buzzer (Chengdu)
- 1. First knowledge of C language (1)
- js判断对象是否是数组的几种方式
- TypeScript快速入门
- Service ability of Hongmeng harmonyos learning notes to realize cross end communication
- String ABC = new string ("ABC"), how many objects are created
- 4. Branch statements and loop statements
- 7. Relationship between array, pointer and array
- 自定义RPC项目——常见问题及详解(注册中心)
- 5月14日杂谈
猜你喜欢

A comprehensive summary of MySQL transactions and implementation principles, and no longer have to worry about interviews

5.MSDN的下载和使用

深度强化文献阅读系列(一):Courier routing and assignment for food delivery service using reinforcement learning

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

【黑马早报】上海市监局回应钟薛高烧不化;麦趣尔承认两批次纯牛奶不合格;微信内测一个手机可注册俩号;度小满回应存款变理财产品...

MySQL锁总结(全面简洁 + 图文详解)

【手撕代码】单例模式及生产者/消费者模式

1. C language matrix addition and subtraction method

优先队列PriorityQueue (大根堆/小根堆/TopK问题)

仿牛客技术博客项目常见问题及解答(一)
随机推荐
MATLAB打开.m文件乱码解决办法
3.猜数字游戏
2. Preliminary exercises of C language (2)
这次,彻底搞清楚MySQL索引
Detailed explanation of redis' distributed lock principle
MySQL事务及实现原理全面总结,再也不用担心面试
魏牌:产品叫好声一片,但为何销量还是受挫
4.分支语句和循环语句
Leetcode. 3. Longest substring without repeated characters - more than 100% solution
Wei Pai: the product is applauded, but why is the sales volume still frustrated
This time, thoroughly understand the MySQL index
[中国近代史] 第九章测验
. Net6: develop modern 3D industrial software based on WPF (2)
编写程序,模拟现实生活中的交通信号灯。
实验五 类和对象
Miscellaneous talk on May 27
20220211-CTF-MISC-006-pure_ Color (use of stegsolve tool) -007 Aesop_ Secret (AES decryption)
Caching mechanism of leveldb
Principles, advantages and disadvantages of two persistence mechanisms RDB and AOF of redis
7-4 散列表查找(PTA程序设计)