1按装 pnpm nuxi init nuxt3-app
2 约定好的路由在pages页面下
3 user/[id].vue 动态路由地址
localhost://3000/user/1,获取参数id $route.params.id=1
const route=useRoute() route.params route.query
localhost://3000/user/1?name=哈哈 $route.query.name=‘哈哈’
user/index.vue 默认路由 localhost://3000/user
4 路由跳转
- nuxt-link to
- a标签 href
5 根组件app.vue
<Nuxt-page></Nuxt-page>
路由出口
默认路由组件pages/index.vue 路由:localhost://3000
默认路由组件pages/user/index.vue 路由:localhost://3000/user
6 父子路由
pages/roles.vue(父组件)-----页面中给一个路由出口
<nuxt-page></nuxt-page>
pages/roles/admin.vue(管理员)-----路由:localhost://3000/roles/admin
pages/roles/normal.vue(普通用户)-----路由:localhost://3000/roles/normal
7 路由的跳转nuxt-link
<nuxt-link to='/'>首页</nuxt-link>
<nuxt-link to='/user'>用户默认页</nuxt-link>
<nuxt-link to='/user/create-or-edit'>用户编辑或新增</nuxt-link>
<nuxt-link to='/roles/admin'>用户--管理员</nuxt-link>
<a href="/about">原始链接跳转,页面会刷新<a/>
// nuxt-link 页面不会刷新
8 动态路由传参
pages/curse/[id].vue 文件目录
localhost://3000/curse/1 页面的路由(动态)
<div>课程id为:{{route.params.id}}</div>
//在script中
const route = useRoute()
9 自定义路由
新建app/router.options.ts文件
const customRutes = [
// 自定义路由
{
path:'/xxx',
name:'xxx',
component:()=>import('@/pages/user/index.vue')
},
{
path:'/yyy',
name:'yyy',
component:()=>import('@/pages/user/index.vue')
},
{
path:'/xxx',
redirect:'/user',
}
]
export default {
routes:(_route)=>_route.concat(customRutes)
}
// 示例页面路由地址:localhost://3000/xxx
10 使用组件全局组件components,直接使用不用导入
//新建文件
components/user/dialog.vue
components/xxx.vue
在页面直接使用组件
<UserDialog/>
<xxx/>
11 SEO和Meta
// 1 在nuxt.config.ts中进行全局配置,不允许使用响应式数据
export default defineNuxtConfig({
app:{
head:{
title:"学无止境",
meta:[
{name:'keywords',content:'不积跬步,无以至千里'},
{name:'description',content:'学海无涯'},
]
}
}
})
//2 使用`useHead`在页面中进行单独响应式的配置,如pages/user/index.vue
useHead({
title:'哈哈哈哈,我是用户页面的标题'
})
// 3 预定义组件
<head>
<Title>{{title}}</Title>
<Mete name='description' :content='title'></Meta>
</head>
// 4 在app.vue根组件中使用标题模板
useHead({
titleTemplate:(chunk)=>{
return chunk?`${chunk}-我是标题`:'我是标题'
},
script:[
{src:'https://www.jd.com',body:ture} //把js文件放在body的最底部
]
})
11 Assets静态文件
public/目录内容原样提供给服务器根目录。
assets/目录按惯例包含你想要构建工具(Vite或webpack)处理的每个资产。
新建文件public/img/a.png ,使用 /img/a.png
新建文件assets/img/b.png ,使用 ~/assets/img/b.png
12 中配置环境变量
1.在 nuxt.config.ts 中配置
// nuxt.config.ts
export default defineNuxtConfig({
runtimeConfig: {
apiSecret: '123', // 只在服务端使用
isServer:true, //可以用来判断在哪个环境执行
// 服务端&客户端都可以使用
public: {
apiBase: '/api'
}
}
})
// 页面中
<script setup>
const runtimeConfig = useRuntimeConfig()
console.log(runtimeConfig.apiSecret)//只在服务端打印,客户端拿不到
console.log(runtimeConfig.public.apiBase) //服务端&客户端都可以打印
</script>
1.在 .env 中配置 (将覆盖nuxt.config.ts中的配置)
// 这将覆盖nuxt.config.ts中apiSecret的值
NUXT_API_SECRET=456
// 这将覆盖nuxt.config.ts中publich下apiBase的值
NUXT_PUBLIC_API_BASE='http://dd.com'
// app.config在构建的时候使用??
12 数据获取
fetch与axios的对,结论:axios在服务端会执行两次,fetch只是在服务端执行一次
useFetch, useLazyFetch, useAsyncData, useLazyAsyncData
//页面中使用
const { data: count } = await useFetch('/api/count')
* useFetch 和 useLazyFetch 的区别:
* 1. 在服务端渲染的时候,这两个没差别
* 2. 在客户端渲染的时候(单页),useLazyFetch 相当于请求是数据是 suspense 的
* 而 useLazyFetch 一定要全部请求完毕,才进行路由内容的显示。
(↑↑↑,这个功能本质是通过 数据获取 | Vue Router 这个实现的)
* 看起来 useFetch 的使用场景会更多一些,除非一些特殊的场景
* useAsyncData 和 useAsyncLazyData 的区别和 fetch 一样
* 只是 useAsyncData 可以接受任何函数和逻辑,返回 Promise(提供了组合的功能)
、、、、、、、、、、、、、、、、
const headers = useRequestHeaders(['cookis','token'])
useRequestHeaders方法可以获取cookie和token等信息
13 服务器接口编写
//创建一个新文件server/api/hello.ts
export default defineEventHandler((event) => {
// 项目中链接数据库,向数据库查询获取数据
return {
name:'小米',
age:'18'
}
// 也可以用这种方式获取到数据
// event.node.res.end()
})
// 在user.vue页面中测试接口
useFetch('/api/hello').then(res=>{
console.log(res,'获取的数据')
})
~/server/api中的文件在它们的路由中会自动以/api作为前缀。 对于添加没有/api前缀的服务器路由,您可以将它们放到 `~/server/routes目录中`
对于上面的例子, /hello路由可以在http://localhost:3000/hello上访问。
// 动态的请求地址`api/hello/[age].ts`可以用 event.context.params.age 来获取
// getQuery() readBody()
sendStream(event,fs.createRedadStream('/api/to.file')) //流操作
// server/api/[...].ts 没有匹配到正确的API地址
14 状态管理
//1 新建文件 : composables/states.ts
export const useCounter = () => useState('counter', () => 0)
export const useColor = () => useState('color', () => 'pink')
// 2 在页面中使用
const counter = useCounter()
const useColor = useColor()
// 也可以使用pinia
npm i @/pinia/nuxt
process.server 判断代码在服务端
process.client 判断代码在客户端
15 自动导入
components
composables
utils
plugins
ref
computed
也可以显性导入
import {ref} from ‘#import’
设置自定义的自动导入
imports:{
dirs:[‘stores’]
}
16 部署 NodeServer
npm run build 打包会生成一个 .output
文件,放到服务器
使用 node .output/server/index.mjs
启动
//安装npm i pm2 -g
//在生产环境 使用 pm2, 请使用 ecosystem.config.js配置文件(在.output文件下新建‘ecosystem.config.js’)
// 运行生产环境
module.exports = {
apps: [
{
name: 'NuxtAppName',
port: '3000',
exec_mode: 'cluster',
instances: 'max',
script: './.output/server/index.mjs',
env:{ }
}
]
}
// 运行项目命令: pm2 start
// 停止项目命令: pm2 stop
// 清除项目命令: pm2 deleta
// 也可以运行某个项目,使用id: pm2 start 1
17 路由渲染模式(部署 NodeServer)
// nuxt.config.ts
export default defineNuxtConfig({
ssr: false, // 整个项目不使用服务端渲染
routeRules: {
// 静态页面按需生成,在后台重新验证
'/blog/**': { swr: true },
// 预渲染,在服务端直接生成静态页面
'/xxx/yyy/zzz': { prerender: true },
// 态页面按需生成一次
'/articles/**': { static: true },
// 设置与路径匹配的自定义标头
'/_nuxt/**': { headers: { 'cache-control': 's-maxage=0' } },
// 使用SPA渲染这些路线,不需要ssr
'/admin/**': { ssr: false },
// 添加cors标头
'/api/v1/**': { cors: true },
// 添加重定向标头
'/old-page': { redirect: '/new-page' },
'/old-page2': { redirect: { to: '/new-page', statusCode: 302 } }
}
})
18 静态托管SSG
npm run generate
打包生成的.output 文件中,server文件是空的,静态文件都在public中
// 默认的动态路由不会自动生成静态文件,需要配置
// 生成动态路由
let routesArr = []
for(let i=1;i<=10;i++){
routesArr.push(`/user/${i}`)
}
defineNuxtConfig({
nitro: {
prerender: {
// routes: ['/user/1', '/user/2'],//固定的路由地址
routes:routesArr // 使用动态生成的路由地址
}
}
})
19 使用组件库
npm i element-plus @element-plus/nuxt -D
export default defineNuxtConfig({
modules: [
'@element-plus/nuxt'
],
elementPlus: { /** Options */ }
})
// 页面中使用
<template>
<el-button @click="ElMessage('hello')">button</el-button>
<ElButton :icon="ElIconEditPen" type="success">button</ElButton>
<LazyElButton type="warning">lazy button</LazyElButton>
</template>
20 nux中配置环境变量
要在 Nuxt 3 中配置环境变量,可以在 `.env` 文件中定义变量,然后在 `nuxt.config.js` 中使用 `process.env` 来引用这些变量。
下面是一个示例:
首先,在项目根目录下新建一个名为 `.env` 的文件,并在其中定义一个环境变量:
API_URL=https://api.example.com
然后,在 `nuxt.config.js` 中使用 `process.env` 来引用这个变量:
```js
export default {
// ...
env: {
apiUrl: process.env.API_URL || 'https://localhost:3000'
},
// ...
}
在这里,我们将 process.env.API_URL
的值设置为 https://api.example.com
。如果没有定义 .env
文件中的 API_URL
变量,它将默认为 https://localhost:3000
。
现在,你可以在应用程序中通过 process.env.apiUrl
引用环境变量了。