vue-router不使用HTML5 History模式记住滚动条位置最佳实践

我这里使用的vuex作为状态管理,当然你也可以换成其他方式,非常简单,只需要修改router全局钩子即可。

router.js示例

import Vue from 'vue'
import Router from 'vue-router'
import store from '../store'
Vue.use(Router)
const routes = [
    {
        path: '/news',
        name: 'topic',
        component: require('../components/topics/index.vue'),
    },
    {
        path: '/news',
        name: 'news',
        component: require('../components/articles/index.vue'),
        meta: {
            title: '科技动态'
        }
    },
]
const router = new Router({routes})
router.beforeEach((to, from, next) => {
    let fromRoute = from.name
    if (fromRoute) {
        let scrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop
        let scrollLeft = document.documentElement.scrollLeft || window.pageXOffset || document.body.scrollLeft
        // let {scrollTop, scrollLeft} = document.documentElement
        store.commit('utils/setScroll', {route: fromRoute, info: {scrollTop, scrollLeft}})
    }
    let toRoute = to.name
    let scroll = store.getters['utils/scroll']
    if (toRoute && undefined !== scroll[toRoute]) {
        let {scrollTop, scrollLeft} = scroll[toRoute]
        window.scrollTo(scrollLeft, scrollTop)
    } else {
        window.scrollTo(0, 0)
    }
    next()
})
export default router

 

store示例:

const namespaced = true
const state = {
    scroll: {}
}
const getters = {
    scroll: state => state.scroll,
}
const mutations = {
    setScroll(state, payload) {
        if (undefined !== payload['route'] && undefined !== payload['info']) {
            state.scroll[payload['route']] = payload['info']
        }
    }
}
const actions = {}
export default {namespaced, state, getters, mutations, actions}