当前位置:网站首页>Nuxtjs快速上手(Nuxt2)
Nuxtjs快速上手(Nuxt2)
2022-07-06 09:21:00 【玲小叮当】
nuxtjs快速上手(nuxt2)
提示:本篇文章是博主观看b站up主前端aka老师视频学习整理的文章
视频指路:《CMS全栈项目》系列九:Nuxt+ElementUI
nuxtjs官网(nuxt2):NuxtJS
文章目录
前言
提示:本篇文章为nuxt2:
本篇文章可以带你快速搭建一个简单的Nuxt.js项目,Nuxt.js 是基于 Vue.js 的通用应用框架,Nuxt.js 预设了利用 Vue.js 开发 服务端渲染(SSR) 的应用所需要的各种配置,文章简要叙述 Nuxt.js 的基础功能,可以快速上手Nuxt!
提示:以下是本篇文章正文内容,下面案例可供参考
一、快速生成nuxt项目
运行 create-nuxt-app
确保安装了 npx (npx 在 NPM 版本 5.2.0 默认安装了):
npx create-nuxt-app <项目名>
或者用 yarn :
yarn create nuxt-app <项目名>

二、nuxtjs配置IP与端口
开发中经常会遇到端口被占用或者指定IP的情况。我们需要在根目录下的 package.json 里对 config 项进行配置。比如现在我们想把IP配置成 127.0.0.1 ,端口设置 8080。
{
...,
"config": {
"nuxt": {
"host": "127.0.0.1",
"port": "8080"
}
//或者
"nuxt": {
"host": "0.0.0.0",
"port": "80"
}
}
}

三、在nuxt中使用less
- 安装
less和 指定版本的less-loader
npm install less less-[email protected]7.0.0 --save-dev
- 全局样式文件
- 在
static目录中创建base.less文件,用来写全局样式。然后打开nuxt.config.js并找到css:
css: [
'element-ui/lib/theme-chalk/index.css',
'~/static/base.less' // 全局样式添加在此处
],
- 组件内样式
<style scoped lang="less">
@bgColor: #f00;
.el-container {
width: 100%;
height: 100%;
.el-main {
color: @bgColor;
height: 100%;
padding: 0;
}
}
</style>
四、nuxtjs中项目清除默认样式
- 打开 reset-css 的
npm网站,随便拿一条链接:
/* 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;
}
- 粘贴代码到
reset.css, 放到static目录下,并在nuxt.config.js引入:
head: {
...,
link: [
{
rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' },
{
rel: 'stylesheet', type: 'text/css', href: '/reset.css' } // 引入
]
},

3. 同样,你也可以放到该文件中的css对象里,以数组项形式存在。
五、nuxtjs中使用asyncData实现SSR
Nuxt可以在asyncData和created中做axios请求。但在created中做请求,渲染出来的数据不会出现在html中,导致无法实现SEO优化,而使用asyncData做请求,则html会被渲染出来,从而实现SSR。不是异步asyncData中不能获取vue的this,所以必须return,template中可直接花括号调用,与使用data数据一致
// 页面中使用asyncData可以实现SSR渲染,但赋值是直接 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 }
})
}
}
六、路由
在page页面中新建vue组件,路由 自动生成 同文件名一致的路由
6.1 动态嵌套子路由
- 可以通过
vue-router的子路由创建Nuxt.js应用的嵌套路由。 - 创建内嵌子路由,你需要添加一个
Vue文件,同时添加一个与该文件同名的目录用来存放子视图组件。 - Warning: 别忘了在父组件(.vue文件) 内增加
<nuxt-child/>用于显示子视图内容。
七、Nuxt解决跨域
- 安装
proxy
npm i @nuxtjs/proxy -D
- 在
nuxt.config.js中添加:
module.exports = {
...,
modules: [
'@nuxtjs/axios',
'@nuxtjs/proxy'
],
axios: {
proxy: true,
prefix: '/',
credentials: true
},
proxy: {
'/api/': {
target: 'http://127.0.0.1:9000/web', // 目标服务器ip
pathRewrite: {
'^/api/': '/',
changeOrigin: true
}
}
}
}
axios的baseURL的话使用/api即可
八、Nuxt.js重定向路由方式
8.1 方式1
通过 nuxt.config.js 设置,在 nuxt.config.js 文件添加下面的配置。redirect 表示重定向的路由。
router: {
extendRoutes(routes, resolve) {
routes.push({
path: '/',
redirect: '/film'
})
}
}
8.2 方式2
通过中间件文件,在目录中的middleware添加一个名为:redirect.js的文件
- 在
redirect.js中写入以下代码,其中path和redirect的路由自己定义。
export default function ({
isHMR, app, store, route, params, error, redirect, }) {
if (isHMR) return; //用来判断热更新
// 页面均放在_lang文件夹下,即lang为动态路由参数;
/* if (!params.lang) { //此写法会出现路由重定向次数过多的问题; return redirect('/' + defaultLocale + '' + route.fullPath)} */
if (route.fullPath == "/") {
return redirect("/home");
}
if (route.fullPath == '/vue') {
return redirect('/vue/basics')
}
}
- 最后需要在
nuxt.config.js文件中添加
router: {
middleware: 'redirect'}

九、nuxt中使用vue插件
- 在
plugins目录下面创建一个xxx.js
import Vue from 'vue'
import VueHighlightJS from 'vue-highlightjs' // 告诉Vue 要使用插件 vue-highlightjs
import 'highlight.js/styles/atom-one-dark.css'
Vue.use(VueHighlightJS)

2. 在nuxt.config.js中配置:
export default {
plugins: ['~/plugins/xxx']
}

总结
提示:这里对文章进行总结:
例如:以上就是今天要讲的 Nuxtjs 内容,本文只是简单介绍了 Nuxtjs 的一些使用,可以让你快速上手 Nuxt,当然 Nuxt 里边还有好多强大的功能,大家可以去官网再详细看看。
边栏推荐
- [the Nine Yang Manual] 2022 Fudan University Applied Statistics real problem + analysis
- The difference between abstract classes and interfaces
- 甲、乙机之间采用方式 1 双向串行通信,具体要求如下: (1)甲机的 k1 按键可通过串行口控制乙机的 LEDI 点亮、LED2 灭,甲机的 k2 按键控制 乙机的 LED1
- FAQs and answers to the imitation Niuke technology blog project (II)
- 【九阳神功】2017复旦大学应用统计真题+解析
- 2. Preliminary exercises of C language (2)
- The latest tank battle 2022 - Notes on the whole development -2
- The latest tank battle 2022 full development notes-1
- The latest tank battle 2022 - full development notes-3
- 【九阳神功】2019复旦大学应用统计真题+解析
猜你喜欢

There is always one of the eight computer operations that you can't learn programming

Mode 1 two-way serial communication is adopted between machine a and machine B, and the specific requirements are as follows: (1) the K1 key of machine a can control the ledi of machine B to turn on a

(超详细onenet TCP协议接入)arduino+esp8266-01s接入物联网平台,上传实时采集数据/TCP透传(以及lua脚本如何获取和编写)

12 excel charts and arrays

2. C language matrix multiplication

Leetcode.3 无重复字符的最长子串——超过100%的解法

使用Spacedesk实现局域网内任意设备作为电脑拓展屏

最新坦克大战2022-全程开发笔记-2

C语言入门指南

更改VS主题及设置背景图片
随机推荐
Cloud native trend in 2022
About the parental delegation mechanism and the process of class loading
仿牛客技术博客项目常见问题及解答(一)
5. Function recursion exercise
Comparison between FileInputStream and bufferedinputstream
Custom RPC project - frequently asked questions and explanations (Registration Center)
View UI plus releases version 1.1.0, supports SSR, supports nuxt, and adds TS declaration files
西安电子科技大学22学年上学期《信号与系统》试题及答案
FAQs and answers to the imitation Niuke technology blog project (I)
Thoroughly understand LRU algorithm - explain 146 questions in detail and eliminate LRU cache in redis
[modern Chinese history] Chapter 9 test
(super detailed II) detailed visualization of onenet data, how to plot with intercepted data flow
1.初识C语言(1)
西安电子科技大学22学年上学期《基础实验》试题及答案
【九阳神功】2016复旦大学应用统计真题+解析
(超详细二)onenet数据可视化详解,如何用截取数据流绘图
Wei Pai: the product is applauded, but why is the sales volume still frustrated
[modern Chinese history] Chapter V test
8. C language - bit operator and displacement operator
杂谈0516