一、浏览器对用户访问网页的记录
二、vue 对访问记录的管理
vue 路由跳转通过对 history,pushState() 和 history.replaceState() 放的模拟来实现的,会往 history 栈中存放一条记录。当调用 router.go() 或者 router.back() 方法时,就和 history.go()、history.back() 效果一样。
三、vue 组件滚动行为
使用 tab 组件进行路由切换,同时对应的子组件重新进行渲染,而不是保存历史滚动的位置信息。
四、如何管理组件的滚动行为
每次切换组件时,让页面回到顶部,router.beforeEach() 导航守卫会是一个不错的选择,当然我们也可以使用 router.afterEach() 导航守卫:
router.afterEach(() => {
// 让页面回到顶部
document.documentElement.scrollTop = 0
})
五、定制不同组件的 scrollBehavior
我们借助 vue-router 提供的 scrollBehavior 来管理组件的滚动行为,可以在组件切换时,回到顶部。
const scrollBehavior = function (to, from, savedPosition) {
// savedPosition 会在你使用浏览器前进或后退按钮时候生效
// 这个跟你使用 router.go() 或 router.back() 效果一致
if (savedPosition) {
return savedPosition
} else {
// 如果不是通过上述行为切换组件,就会让页面回到顶部
return {x: 0, y: 0}
}
}
这里用路由的元信息 meta 来控制滚动行为。
const routes = [
// 设置 meta,细颗粒控制组件滚动
{path: '/', component: Home, meta: {x: 0, y: 0}},
{path: '/list', component: List, meta: {x: 0, y: 0}},
{path: '/about', component: About, meta: {x: 0, y: 0}}
]
const scrollBehavior = function (to, from, savedPosition) {
return to.meta
}
const router = new VueRouter({
routes,
scrollBehavior,
linkExactActiveClass: 'current'
})
在 vue 中全局监听滚动事件(绑定到 vue 根实例上),因为 this 会自动绑定到当前上下文:
new Vue({
router,
data: {
timerId: ''
},
mounted () {
window.addEventListener('scroll', this.justifyPos)
},
methods: {
justifyPos () {
if (this.timerId) clearTimeout(this.timerId)
this.timerId = setTimeout(() => {
this.$route.meta.y = window.pageYOffset
}, 300)
}
}
}).$mount('#app')