昨天初始化了一个Nuxt3项目,一打开项目发现Nuxt3的脚手架可以说是很苗条了。从命令行搭建到项目的目录结构一切都很简洁,索性前人栽树后人乘凉,遇事不觉先B站刷波视频。今天记录一下Nuxt3神奇的路由使用体验。
-
认识几个新标签
<!-- Nuxt3的首页,暂不清楚如何实现,感觉就是高端大气上档次 -->
<NuxtWelcome/>
<!-- 类比于vue-router中的router-view,可以看做一个容器,
路由指向哪里该容器就装入对应的页面 -->
<NuxtPage/>
<!-- 作用同<NuxtPage/>,区别在于该标签用于父级页面中作为子页面的容器 -->
<nuxt-child/>
<!-- 类比与router-link -->
<nuxt-link to="xxx"></nuxt-link>
-
搞个极其简单的文章超链接列表
文章列表
// pages/index.vue
<template>
<div>
the minimalist article list
<br>
<nuxt-link to="./article-1">to article1</nuxt-link><br>
<nuxt-link to="./article-2">to article2</nuxt-link><br>
<nuxt-link to="./article-3">to article3</nuxt-link>
</div>
</template>
文章详情
// pages/article-[indexCode]/index.vue
<template>
<div>
文章id: {{$route.params.indexCode}}
</div>
</template>
首页效果
点击article2进入详情页
Point
-
按Nuxt3的约定创建pages目录结构,Nuxt3已经基于这种约定为我们封装好了路由,它会将我们的目录结构最终映射为router配置
-
Nuxt3巧妙的使用文件目录结构映射出路由配置从而省去开发者编写路由配置文件,同时它将这种优越性发挥到了路由传参上,上述例子详情页所在的目录文件夹命名至关重要,Nuxt3通过‘[xxx]’存放路由传递的参数
- 该文件目录相当于以下路由配置
import homepage from '../index.vue'
import detailPage from './index.vue'
export const router = [
{
path: '/',
component: homepage
},
{
page: '/article/:id'
}
]
-
搞个极其简单的tab切换子路由
文件目录
-| pages/
---| tab/
-----| tab1.vue
-----| tab2.vue
---| tab.vue
tab.vue
<template>
<div>
<nuxt-link to="/tab/tab1">to article1</nuxt-link><br>
<nuxt-link to="/tab/tab2">to article2</nuxt-link><br>
<nuxt-child />
</div>
</template>
tab1.vue
<template>
<div>
我是tab1内容
</div>
</template>
Ponint
- 使用同名目录和vue文件来表示路由的父子关系
- 使用 nuxt-child 标签作为子路由页面的容器
-
总结
- 目前这种基于约定的路由官方暂未发布路由守卫、重定向配置方式
- 暂未实现对目录结构的watcher,导致修改新增或修改目录结构之后需要重启
- 路由传参是使用
routere的parmas属性,暂未发现query方式传参 - 使用
NuxtLink时,to的参数误传作了‘./tab/tab1’,路由应该匹配的是‘/tab/tab1’不需要加‘.’,确实也找不到加‘.’的理由