Skip to content

Instantly share code, notes, and snippets.

@agileago
Created December 4, 2018 13:33
Show Gist options
  • Save agileago/d2b3522fb6c1b3cf5f4d7f0b38557e38 to your computer and use it in GitHub Desktop.
Save agileago/d2b3522fb6c1b3cf5f4d7f0b38557e38 to your computer and use it in GitHub Desktop.
移动端路由切换动画处理
export default function historyManage (store, router) {
store.registerModule('transition', {
state: {
direction: ''
},
mutations: {
UPDATE_DIRECTION (state, direction) {
state.direction = direction
}
}
})
const history = window.sessionStorage
history.clear()
let historyCount = 0
history.setItem('/', 0)
var isFirst = true
// 解决ios左滑返回再次执行动画
let isPush = false
let endTime = Date.now();
let isTouchStart = false;
let direction = '';
['push', 'replace', 'go', 'back', 'forward'].forEach(key => {
let method = router[key].bind(router)
router[key] = function () {
isPush = true
method.apply(null, arguments)
}
})
router.beforeEach(function (to, from, next) {
const toIndex = history.getItem(to.path)
const fromIndex = history.getItem(from.path)
if (toIndex) {
if (!fromIndex || parseInt(toIndex, 10) > parseInt(fromIndex, 10)) {
if (!isPush && ((Date.now() - endTime) < 377 || isTouchStart)) {
direction = ''
} else {
direction = 'in'
}
} else if (toIndex === '0' && fromIndex === '0') { // 进来就是首页
direction = ''
} else {
if (!isPush && ((Date.now() - endTime) < 377 || isTouchStart)) {
direction = ''
} else {
direction = 'out'
}
}
} else {
++historyCount
history.setItem('count', historyCount)
to.path !== '/' && history.setItem(to.path, historyCount)
if (!isFirst) direction = 'in'
}
isTouchStart = false
isFirst = false
store.commit('UPDATE_DIRECTION', direction)
next()
})
router.afterEach((to, from) => {
isPush = false
})
document.addEventListener('touchstart', e => {
isTouchStart = true
endTime = Date.now()
})
document.addEventListener('touchend', e => {
isTouchStart = false
endTime = Date.now()
})
document.addEventListener('touchcancel', e => {
isTouchStart = false
endTime = Date.now()
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment