1874
1874
FE Engineer
桌游布道者
有粤语歌就不会有世界末日

在Vue中维护路由跳转记录

1874 - 2021-02-01 - 技术分享 / Vue
2021-2-1|最后更新: 2023-4-10|
type
Post
status
Published
date
Feb 1, 2021
slug
hemk59
summary
本文介绍了如何在Vue中维护路由跳转记录,以解决使用this.$router.go(-1)返回上一个路由时,无法拿到上个路由的路由地址的问题,并避免进入死循环。作者提出了通过路由守卫,利用堆栈的方式维护页面跳转的历史记录的思路,并给出了具体实现方法。
category
技术分享
tags
Vue
创建时间
Apr 7, 2023 07:15 PM
更新时间
Apr 10, 2023 05:56 AM
password
icon
Task List

引言

在 vue 中我们可以用this.$router.go(-1)返回上一个路由,但无法拿到上个路由的路由地址,这样就出现一个问题就是如果我上个路由是中转页面,作用就是跳到下个页面,这个时候的this.$router.go(-1)就不起作用,进入了死循环。 所以网上找了下一个比较好的办法就是利用路由守卫,维护自己的路由跳转记录。

思路

  1. 实现一个Vue工具history.js,通过堆栈的方式维护页面跳转的历史记录,控制返回跳转。
  1. 扩展一个获取上个路由的方法。
  1. 在全局路由router.js中,实例化路由前,通过原型扩展routergoBack()方法
  1. router路由守卫afterEach的生命周期中存放历史记录。

实现

// src/utils/history.js const History = { _history: [], // 历史记录堆栈 install(Vue) { // 提供Vue插件所需安装方法 Object.defineProperty(Vue.prototype, '$routerHistory', { get() { return History }, }) }, push(path) { // 入栈 this._history.push(path) }, pop() { this._history.pop() }, canBack() { return this._history.length > 1 }, lastHistory() { return this._history.length > 1 ? this._history[this._history.length - 2] : '/' }, } export default History
在路由实例化之前,扩展back()方法
// src/router/index.js import Vue from 'vue' import Router from 'vue-router' import History from './utils/history'; Vue.use(Router); Vue.use(History); // 实例化之前,扩展Router Router.prototype.goBack = function () { this.isBack = true; this.back(); }
在路由全局afterEach中记录跳转历史
// src/router/index.js import History from './utils/history'; // afterEach记录历史记录 router.afterEach((to, from) => { if (router.isBack) { // 后退 History.pop(); router.isBack = false; router.transitionName = 'route-back'; } else { History.push(to.path); router.transitionName = 'route-forward'; } })
在页面中使用
if (this.$routerHistory.lastHistory().indexOf('/router') !== -1) { this.$router.push({ path: '/', }) } else { this.$router.goback() }
Webpack配置-多进程/多实例解析资源前端开发规范之Eslint