路由的前进后退
在浏览器中,有历史记录可以供用户手动选择前进后退到指定的历史纪录那,那么前端是怎么实现路由的前进后退呢?
本次讲解将通过下面的例题来分析:
- 利用脚手架创建好项目
# 创建项目 v-mapp
命令行输入:vue create v-mapp
# 项目插件选择自定义安装
选择:Manually select features
# 选择插件
选择:Choose Vue version 、Babel 、Router 、CSS Pre-processors
# 安装好后然后根据提示
cd 目录
npm run serve
- 在
src
下创建view
或page
文件夹,再创建对应的Box.vue
和Foo.vue
文件
# Box.vue文件内容
<template>
<div>box</div>
</template>
<script>
export default {
}
</script>
<style>
</style>
# Foo.vue文件内容
<template>
<div>box</div>
</template>
<script>
export default {
}
</script>
<style>
</style>
- 在
router
文件夹的index.js
文件夹内进行配置
// 引入路由管理的组件
import Box from '../pages/Box'
import Foo from '../pages/Foo'
// 使用插件
Vue.use(VueRouter);
// 创建路由对象
const router = new VueRouter(
// 路由的配置项
{
//路由配置表
routes: [
// 一个路由的配置对象
{
// 当浏览器地址发生变化为'/box'地址时,那么路由需要显示Box组件。
path: "/box",
component: Box,
},
{
path: "/foo",
component: Foo,
}
],
mode: 'hash'
}
);
- 对 App.vue 文件进行配置,并在其中添加路由的前进、后退、进入、返回等方法
<template>
<div id="app">
<h1>app</h1>
<router-link to="/box">one</router-link>
<router-link to="/foo">two</router-link>
<button @click="btn1Action">进入路由</button>
<button @click="btn2Action">替换路由</button>
<button @click="btn3Action">前进</button>
<button @click="btn4Action">返回</button>
<button @click="btn5Action">go</button>
<hr/>
<!-- 当地址发生变化,路由匹配到了路由表中的对象,那么会将对应的组件显示在router-view组件中 -->
<router-view></router-view>
</div>
</template>
<script>
export default {
methods: {
btn1Action(){
// this.$router就是Vue实例下配置的路由对象
// this.$router.push('/foo');
this.$router.push({path: '/foo'});
},
btn2Action(){
// this.$router.replace('/foo');
this.$router.replace({path: '/foo'});
},
btn3Action(){
// 前进
this.$router.forward();// go(1)
},
btn4Action(){
// 后退
this.$router.back(); //go(-1)
},
btn5Action(){
// go() 接收数字的参数,表示前进或后退多少个历史记录。
this.$router.go(2);
}
}
}
</script>
<style>
a{
padding: 10px;
}
.router-link-active{
color: green;
}
</style>
注意:$route 是“路由信息对象”,它包括 path、params、hash、query等路由信息参数;
而 $router 是“路由实例”对象, 它包括了路由的跳转方法、钩子函数等。