scrollBehavior可以让我们在进行路由跳转后页面滚动到固定的位置,增加用户的体验度。
scrollBehavior的返回值为一个对象,里面包含x轴跟y轴长度:
return {
x: 0,
y: 900
}
在定义路由跳转时,对to的路由添加hash属性,属性值为某个标签的id
可简写为"/path#id"
this.$router.push('/path#router-link')
然后在指定位置的标签添加相应id
<div id="router-link">
<keep-alive >
<router-view v-if="$route.meta.keepAlive"></router-view>
</keep-alive>
<router-view v-if="!$route.meta.keepAlive"></router-view>
</div>
router.js:
scrollBehavior(to, from, savedPosition) {
if (savedPosition) {
return savedPosition;
}
const position = {}
if (to.hash) {
position.selector = to.hash //保存此id标签的位置属性
return position
}
}
savedPosition可以在浏览器前进后退行为中保留上一个路由的位置