概述
标记当次浏览为第一个访问页面的方法。
内容
方法
当页面第一次载入时,查询sessionStorage中的firstPageKey。如果有则保存到变量中;如果没有则保存当前时间戳到内存,并记录在sessionStorage中,同时使用history.replaceState保存状态到历史记录中。
在路由跳转的过程中,可以通过比较变量中的firstPageKey与history.state.firstPageKey是否一致来判断是否是浏览的第一个页面。
页面的刷新不会影响除了当前页面的历史记录,所以在非第一个页面的刷新不会影响保存的历史状态,同时由于firstPageKey保存到了sessionStorage中,比较功能也不受影响。但需要注意的是,如果是刷新第一个页面,那么历史状态也会被替换。这时需要监听刷新来清除sessionStorage中的firstPageKey,让上述过程得已重复。
Vue示例
const state = { // vuex
firstPageKey: +sessionStorage.getItem('firstPageKey') || 0 // 第一个页面的key,优先从sessionStorage中取
}
const mutations = {
setFirstPageKey(state, { key = Date.now() } = {}) {
if (!state.firstPageKey) { // 只有值不存在时设置,即不更新值
state.firstPageKey = key
sessionStorage.setItem('firstPageKey', key)
history.replaceState({ firstPageKey: key }, null, null)
}
}
}
router.afterEach((to, from) => { // vue-router
store.commit('router/setFirstPageKey') // 放在afterEach里确保在vue-router的路由跳转完成后执行
})
window.addEventListener('unload', () => { // 监听刷新(通过页面卸载事件)
if (state.firstPageKey === history.state.firstPageKey) {
sessionStorage.setItem('firstPageKey', 0)
}
})
history.state.firstPageKey === state.firstPageKey // 通过比较判断当前页面是否为第一个页面
来源:oschina
链接:https://my.oschina.net/skywingjiang/blog/4465343