【笔记】Nuxt学习笔记

前言

Nuxt.js是一个免费且开放源代码的Web应用框架,基于Vue.js、Nitro以及Vite。Nuxt.js的灵感来源于作用类似但基于React.js的框架Next.js。(维基百科)

创建项目

npm

1
2
npx nuxi init <project_name>
cd <project_name>

pnpm

1
2
pnpm dlx nuxi init <project_name>
cd <project_name>

下载依赖

npm

1
npm install

yarn

1
yarn install

pnpm

1
pnpm install --shamefully-hoist

基本命令

打包项目

1
nuxt build

打包项目并提前渲染路由

1
nuxt generate

打包项目并在本地预览

1
nuxt preview

运行项目

1
nuxt dev

生成预制文件

  • 生成.next/目录和*.tx文件
  • 在npm install之后会自动执行nuxt prepare
1
nuxt prepare

配置文件

定义配置

  • Nuxt允许省略引入语句

runtimeConfig:运行时配置,可以通过环境变量覆盖

key1:定义在public外部表示仅服务端配置
key2:定义在public内部表示客户端和服务端配置

appConfig:应用配置,构建时变量
app:应用页面配置

app.head:所有页面的<head></head>配置

ssr:是否是SSR项目

true:缺省值,SSR项目
false:SPA项目

router:路由配置

router.options.hashMode:在SPA模式下切换路由模式为Hash模式

nuxt.config.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// import { defineNuxtConfig } from "nuxt/config";

export default defineNuxtConfig({
runtimeConfig: {
key1: "value",
public: {
key2: "value"
}
},
appConfig: {
key3: "value"
},
app: {
head: {
title: "",
charset: "UTF-8",
viewport: "",
meta: [
{
name: "keywords",
content: ""
},
{
name: "description",
content: ""
}
],
link: [
{
rel: "",
href: "favicon.ico",
type: "image/x-icon"
}
],
style: [
{
children: "body { color: red }"
}
],
script: [
{
src: "",
body: true
}
]
}
},
ssr: false,
router: {
options: {
hashMode: true
}
}
});

通过环境变量覆盖runtimeConfig运行时配置

  • 使用全大写的、以NUXT_为前缀的蛇形命名环境变量覆盖对应的小驼峰命名的运行时配置
.env
1
2
NUXT_KEY1 = ""
NUXT_PUBLIC_KEY2 = ""

在页面内修改app配置

通过useHead()修改页面配置
App.vue
1
2
3
4
5
6
7
8
<script setup>
useHead({
title: "",
bodyAttrs: {
class: ""
}
});
</script>
通过SEO组件修改页面配置
App.vue
1
2
3
4
5
6
7
<template>
<Head>
<Meta name="" content="">
<Style></Style>
<Link></Link>
</Head>
</template>
  • 省略<Head></Head>
App.vue
1
2
3
4
5
<template>
<Meta name="" content="">
<Style></Style>
<Link></Link>
</template>

使用运行时配置

App.vue
1
2
3
4
5
6
7
8
9
10
11
12
<script setup>
const runtimeConfig = useRuntimeConfig();

if (process.server) {
console.log(runtimeConfig.key1);
console.log(runtimeConfig.public.key2);
}

if (process.client || typeof window === "object") {
console.log(runtimeConfig.public.key2);
}
</script>

使用应用配置

App.vue
1
2
3
4
5
6
7
<script setup>
const appConfig = useAppConfig();

onMounted(function () {
console.log(appConfig.key3); // "value"
});
</script>

路由

首页

pages/index.vue
1
<template></template>
App.vue
1
2
3
<template>
<NuxtPage></NuxtPage>
</template>

完成