一、路由
Nuxt路由官网上的API详解:点击链接
Nuxt.js 依据 pages 目录结构自动生成 vue-router 模块的路由配置。
(1) 要在页面之间使用路由,我们建议使用 标签。 支持activeClass ,tag
基础路由:
layout/default.vue默认布局:
<template>
<div>
<!-- 跳转 -->
<nuxt-link to="/user/one" tag="li" activeClass="active">filem</nuxt-link>
<!-- <nuxt /> 一级路由容器 -->
<nuxt />
</div>
</template>
假设 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'
}
]
}
嵌套路由:
1.创建内嵌子路由,你需要添加一个 Vue 文件,同时添加一个与该文件同名的目录 用来存放子视图组件。
2.Warning: 别忘了在父组件(.vue文件) 内增加 用于显示子视图内 容。
看了官网上的api实现了官网的案例你会发现访问父页面中只能显示父页面中的内容,要想默认的在<nuxt-child>区域显示一个页面内容怎么办?
自己案例代码:
pages/parent.vue
<template>
<div>
<h2>父组件的页面的内容</h2>
<ul>
<!-- 进行切换子页面,写法同vue.js -->
<li><nuxt-link to='/parent/child'>child</nuxt-link></li>
<li><nuxt-link to='/parent/child2'>child2</nuxt-link></li>
</ul>
<hr>
<div class="box">
<p>嵌套子页面内容区</p>
<!-- <nuxt-child>标签在父页面组件中相当于是子页面组件的占位符;嵌套中这个不可少 -->
<nuxt-child keep-alive :foobar="123"></nuxt-child>
</div>
</div>
</template>
<script>
export default {
}
</script>
<style scoped>
.box{
margin-top: 20px;
padding: 20px;
border: 2px solid pink;
border-radius: 5px;
}
</style>
pages/parent/index.vue
<template>
<div>
<h2>嵌套子组件中的默认页面index.vue</h2>
</div>
</template>
<script>
export default {
}
</script>
<style scoped>
</style>
pages/parent/child.vue
<template>
<div>
<h2>嵌套子组件中的页面child</h2>
<p>foobar:{{foobar}}</p>
</div>
</template>
<script>
export default {
props:['foobar']
}
</script>
<style scoped>
</style>
pages/parent/child2.vue
<template>
<div>
<h2>嵌套子组件中的页面child2</h2>
<p>foobar:{{foobar}}</p>
</div>
</template>
<script>
export default {
props: ['foobar']
}
</script>
<style scoped>
</style>
效果如下:
重定向:
a. nuxt.config.js
// 配置重定向
router: {
extendRoutes(routes, resolve) {
routes.push({
path: '/',
redirect: '/film'
})
}
},
b. 利用中间件来处理
// 中间件 middle/ redirect.js
export default function({
isHMR,
app,
store,
route,
params,
error,
redirect
}) {
if (isHMR) return
// 页面均放在_lang文件夹下,即lang为动态路由参数
/*if (!params.lang) { //此写法会出现路由重定向次数过多的问题
return redirect('/' + defaultLocale + '' + route.fullPath)
}
*/
if (route.fullPath == '/film') {
return redirect('/film/nowplaying')
}
}
router: {
middleware: 'redirect' // 即每次路由跳转会调用该中间件
//多个中间件写法
// middleware: ['redirect']
}
动态路由:
在 Nuxt.js 里面定义带参数的动态路由,需要创建对应的以下划线作为前缀的 Vue 文件 或 目录。
pages/
‐‐| detail/
‐‐‐‐‐| _id.vue
//编程式跳转 this.$router.push("/detail");
//获取动态路由参数 <div>detail-{{ $route.params.id }}</div>
获取动态路由参数
asyncData({params}){
console.log(params.id);
}