History

History

通过vue-router的onRouteChangeBefore事件构建本地历史记录

问题

单页应用的一个需求是需要知道路由切换是前进还是后退, 但是浏览器对路由切换只给了两个事件 hashchangepopstate, 故无从判断当前操作是后退还是前进.

解决方案

这个类通过vue-router的onRouteChangeBefore事件构建本地历史记录. 当路由切换时, 内建历史记录数组, 类似于一个stack, 这个能正确反映当前app的浏览历史记录.

完成的功能如下:

  • 内建导航记录
  • 此History是对router实例的拓展, 但是不会为router实例添加方法, 而是重新定义$history, 这个可在业务的this中访问到

构造器 / Constructor

new History()

源码:

方法 / Methods

canGoBack() → {Boolean}

源码:

判断是否能返回

getDirection() → {string}

源码:

获取当前的页面进行的方向
只能是这两个值: forward || backward

getHistory() → {Array}

源码:

获取当前的导航记录

toRoot()

源码:

返回root页面(在路由信息中标示route.meta.root=true的页面)

示例 / Example
{
   path: '/',
   name: 'index',
   meta: {
     root: true
   },
   component: require('@/pages/index.vue')
}