初步搞了个记录H5浏览记录的方法,主要是为了解决最后那张图上页面跳转的问题,不知道还有没有其他问题,欢迎指正!
export default class History {
key: string; // 缓存用到的key
history: Array<string | null> // 记录path数组
active: number // 当前活跃path的下标
constructor() {
this.key = 'x_history';
this.history = [null]
this.active = 0
}
// 记录path方法
record() {
this.getSession()
let state = window.history.state
this.active = state.position
this.history[state.position] = state.current
if (state.forward) {
this.history[state.position + 1] = state.forward
} else {
this.history.splice(state.position + 1, this.history.length - state.position - 1)
}
if (state.back) {
this.history[state.position - 1] = state.back
}
this.setSession()
}
// 获取历史记录
getHistory() {
this.getSession()
let history = this.history
let active = this.active
return { history, active }
}
// 获取指定path的位置INDEX
getHistoryIndex(path: string) {
this.getSession()
return this.history.findIndex(item => item === path)
}
// 设置缓存
setSession() {
let history = this.history
let active = this.active
window.sessionStorage.setItem(this.key, JSON.stringify({
history, active
}))
}
// 获取缓存
getSession() {
let { history, active } = (JSON.parse(window.sessionStorage.getItem(this.key) as string) || { history: this.history, active: this.active })
this.history = history
this.active = active
}
}
![](https://img.haomeiwen.com/i24739582/640d751475b2f04b.png)
网友评论