一、重定向
有的时候,我们会根据某种需求对用户请求的页面进行重新定位
1.1案例(需求)
现有一小说网站,提供了 男生频道 和 女生频道 的两个入口,用户首次进入页面的时候,会出现选择,并记住用户的选择,以后该用户进入网站直接根据记录的选择进入对应的频道
1.2组件
//App.Vue
<template>
<div id="app">
<h1>vue-router</h1>
<div id="nav">
<router-link to="/">Home</router-link> |
<router-link to="/about">About</router-link> |
<router-link to="/user">User</router-link> |
<router-link to="/bookType">BookType</router-link>
</div>
<hr>
<!-- 显示主页 -->
<router-view></router-view>
</div>
</template>
通过localStorage和beforeRouteLeave两种方式实现重定向:
// BookType.vue
<template>
<div>
<router-link :to="{name: 'bookBoy'}">男频</router-link>|
<router-link :to="{name: 'bookGirl'}">女频</router-link>
</div>
</template>
<script>
export default {
name: "BookType",
// 方法一:通过生命周期实现
// 通过localStorage决定跳转到哪个频道
beforeRouteEnter(to, from, next) {
let bookType = localStorage.getItem('book-type');
if ( ['bookBoy', 'bookGirl'].includes(bookType) ) {
// this.$router.push({name: bookType})
next(vm => {
vm.$router.push({name: bookType})
})
} else {
next();
}
},
// 方法二:通过组件内守卫实现
// beforeRouteLeave(to, from, next) {
// let bookType = to.name;
// console.log(bookType);
// if (["bookBoy", "bookGirl"].includes(bookType)) {
// // 记录当前的路由名称
// localStorage.setItem("book-type", bookType);
// }
// next();
// }
};
</script>
<style>
</style>
// BookBoy.vue
<template>
<div>
男频
</div>
</template>
<script>
export default {
name: 'BookBoy',
created(){
// 点击频道后,首先记录点击动作到localStorage
localStorage.setItem("book-type","bookBoy");
}
}
</script>
// BookGirl.vue
<template>
<div>
女频
</div>
</template>
<script>
export default {
name: 'BookGirl',
created(){
// 点击频道后,首先记录点击动作到localStorage
localStorage.setItem("book-type","bookGirl");
}
}
</script>
1.3路由配置
注意:导航时使用/bookType,当已选择过book-type时会直接返回已有的booktype;
当没有选择过时返回默认的book路由,此时会直接导航至bookType.Vue组件
//route.js
// 书城
{
name: "bookType",
path: '/BookType',
redirect: to => {
//作为中间男女频跳转的媒介,没有真正的Book模板
let type = localStorage.getItem("book-type");
console.log(type)
return { name: type || "book" };
}
},
{
// 第一次进入书城,在没有选择男频女频前,需要点击bookType就链接到全频书城,
// 但是在BookType路由中,如果直接写 return { name: type || "bookType" };自己再次路由到自己就会报错,所以需要设置第三方中介路由
name: 'book',
path: '/Book',
// component: BookType
component: () =>
import ('@/components/book/BookType.vue'),
},
{
name: "bookBoy",
path: '/BookBoy',
// component: BookBoy,
component: () =>
import ('@/components/book/BookBoy.vue')
},
{
name: "bookGirl",
path: '/BookGirl',
// component: BookGirl,
component: () =>
import ('@/components/book/BookGirl.vue')
},
二、别名
重定向,是从一个路由切换到另外一个路由,而别名是不同的路由显示同一个页面,比如:/user
是用户中心的路由,/member
,我们也可以给这个页面定义另外一个路由,虽然在某些时候,重定向与别名有类似的效果,但是,别名不存在跳转,浏览器地址栏上显示的 URL 并不会切换
{
path: '/user',
alias: '/member'
component: User,
}
三、404
// 错误页面
import NotFound from '@/components/NotFound.vue'
{
path: '*',
component: NotFound
}
//NotFound.vue
<template>
<div>
此页面不存在!!!
</div>
</template>
<script>
export default {
name: "NotFound"
}
</script>