路由教程
Nuxt.js 依据 pages
目录结构自动生成 vue-router 模块的路由配置。
要在页面之间使用路由,我们建议使用 标签。
例如:
首页
基础路由
假设 pages
的目录结构如下:
pages/
--| user/
-----| index.vue
-----| one.vue
--| index.vue
那么,Nuxt.js 自动生成的路由配置如下:
router: {
routes: [
{
name: 'index',
path: '/',
component: 'pages/index.vue'
},
{
name: 'user',
path: '/user',
component: 'pages/user/index.vue'
},
{
name: 'user-one',
path: '/user/one',
component: 'pages/user/one.vue'
}
]
}
第六步:在page文件夹下,新建demo.vue文件
<template>
<div>
demo
</div>
</template>
<script>
export default {
}
</script>
<style>
</style>
此时,会自动生成路由地址
在网址中直接输入localhost:3000/demo
,查看demo.vue
文件内容
显示——>demo
第七步:新建文件夹user和子文件_id.vue
user/_id.vue
中
<template>
<div>
用户详情
{{ $route.params.id }}
<nuxt-link to="/">首页</nuxt-link>
</div>
</template>
<script>
export default {
// 每一个页面的组件都有一个validate,可以对参数 做校验
validate ({ params }) {
// 必须是number类型
return /^\d+$/.test(params.id)
}
}
</script>
<style>
</style>
第八步:在网址中输入localhost:3000/user/12
,可看到——>用户详情12
第九步:路由参数校验:https://zh.nuxtjs.org/guide/routing
Nuxt.js 可以让你在动态路由组件中定义参数校验方法。
举个例子: pages/users/_id.vue
export default {
validate ({ params }) {
// 必须是number类型
return /^\d+$/.test(params.id)
}
}
如果校验方法返回的值不为 true
或Promise
中resolve 解析为false
或抛出Error , Nuxt.js 将自动加载显示 404 错误页面或 500 错误页面。
想了解关于路由参数校验的信息,请参考 页面校验API。
示例:
2.访问地址localhost:3000/user/234
,会显示——>用户详情 234
3.当id不是数字时,校验返回false,访问地址localhost:3000/user/abc
,会显示404页面
第十步:嵌套路由:教程
你可以通过 vue-router 的子路由创建 Nuxt.js 应用的嵌套路由。
创建内嵌子路由,你需要添加一个 Vue 文件,同时添加一个与该文件同名的目录用来存放子视图组件。
Warning: 别忘了在父组件(
.vue
文件) 内增加用于显示子视图内容。
假设文件结构如:
pages/
--| users/
-----| _id.vue
-----| index.vue
--| users.vue
Nuxt.js 自动生成的路由配置如下:
router: {
routes: [
{
path: '/users',
component: 'pages/users.vue',
children: [
{
path: '',
component: 'pages/users/index.vue',
name: 'users'
},
{
path: ':id',
component: 'pages/users/_id.vue',
name: 'users-id'
}
]
}
]
}
操作:
1.新建文件夹user的子文件user/test.vue
<template>
<div>
user-test
<nuxt-link to="/">首页</nuxt-link>
</div>
</template>
<script>
export default {
}
</script>
<style>
</style>
2.新建文件夹user同层级文件pages/user.vue
文件
<template>
<div>
<h1>这是用户管理</h1>
<nuxt-child />
</div>
</template>
<script>
export default {
}
</script>
<style>
</style>
3.访问用户详情页面
访问test页面
对比:
之前是这么写的嵌套路由-子路由,在router.js
中,父子路由结构如:
Vue.use(Router)
const router = new Router({
//父路由
routes: [{
path: '/',
component: Layout,
//子路由
children: [
{ path: '/', name: 'home', component: Home, meta: { keepAlive: true } },
{ path: '/question', name: 'question', component: Question },
{ path: '/video', name: 'video', component: Video },
{ path: '/user', name: 'user', component: User }
]
},
{ path: '/user/profile', name: 'user-profile', component: UserProfile },
{ path: '/user/chat', name: 'user-chat', component: UserChat },
{ path: '/login', name: 'login', component: Login },
{ path: '/search', name: 'search', component: Search },
{ path: '/search/result', name: 'search-result', component: SearchResult },
{ path: '/article/:id', name: 'article', component: Article, meta: { keepAlive: true } }
]
})