自动注册
- 根据 pages 目录下的文件路径,自动注册成对应的前端路由
- 建议页面组件也放到全局 components 目录下,不要在pages目录下新建组件,否则会被自动注册成页面路由
- 如果存在同名的vue组件和目录,vue组件的优先级高,且同名目录下的vue组件无法被注册成路由,同名目录下的vue组件只能通过嵌套路由访问
静态路由
修改 app.vue
<template>
<!-- 相当于router-view, 发现直接用router-view也行 -->
<NuxtPage />
</template>
新建pages目录
- 如果创建了pages目录,首页默认指向pages/index.vue
| 目录 | 路由 |
|---|---|
| pages/index.vue | http://localhost:3000/ |
| pages/home.vue | http://localhost:3000/home |
| pages/parent/index.vue | http://localhost:3000/parent |
| pages/parent/info.vue | http://localhost:3000/parent/info |
嵌套路由
同名vue组件和目录
| 目录 | 路由 |
|---|---|
| pages/parent.vue | http://localhost:3000/parent |
| pages/parent/index.vue | 无法访问 |
| pages/parent/info.vue | 无法访问 |
使用嵌套路由访问
// pages/parent.vue
<template>
<div>
parent page
<NuxtPage />
</div>
</template>
动态路由
如果文件和文件名中有中括号 "[]", 就代表该参数数一个动态参数。 且在页面中,我们可以直接通过$route对象访问组件内动态参数
路由跳转
使用 navigateTo
navigateTo是nuxt3内置的可使用编程导航的方法navigateTo在服务端和客户端均生效,也可跳转外链- 始终使用 await 或 return on navigateTo 的结果
await navigateTo('/home')
await navigateTo({ path: '/home' })
await navigateTo({ path: '/search', query: { page: 1, sort: 'asc' }})
// 跳转外链
await navigateTo('https://v3.nuxtjs.org', { external: true})
使用 router
const router = useRouter()
router.push()