对Vue的理解

路由的前进后退

在浏览器中,有历史记录可以供用户手动选择前进后退到指定的历史纪录那,那么前端是怎么实现路由的前进后退呢?

本次讲解将通过下面的例题来分析:

  1. 利用脚手架创建好项目
# 创建项目 v-mapp
命令行输入:vue create v-mapp
# 项目插件选择自定义安装
选择:Manually select features
# 选择插件
选择:Choose Vue version 、Babel 、Router 、CSS Pre-processors
# 安装好后然后根据提示
cd 目录
npm run serve
  1. src 下创建 viewpage 文件夹,再创建对应的 Box.vueFoo.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>
  1. 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'
  }
);
  1. 对 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 是“路由实例”对象, 它包括了路由的跳转方法、钩子函数等。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值