vue 讓元素回到頂部
在切換路由時,我們需要讓頁面回到頂部,有以下幾種方式:
一、router
在router中
// 回到頂部
router.afterEach((to, from, next) => {
window.scrollTo(0, 0);
})
二、滾動條不在body上
例如:
<template>
<!--.wrap-box元素固定高度,內容溢出時,該元素縱向滾動-->
<div class="wrap-box" ref="scollElement">
<!--.box元素超出父元素.wrap-box高度時,頁面會出現滾動條(滾動元素爲.wrap-box)-->
<div class="box">
<!--內容區(切換不同模塊)-->
<router-view></router-view>
</div>
</div>
</template>
<script>
export default{
name:'warp-box',
updated () { // 切換不同模塊時觸發
this.$nextTick(()=>{
if(this.$refs.scollElement){ // 滾動元素跳轉到頂部
this.$refs.scollElement.scrollTop = 0;
}
})
}
}
</script>
<style>
.wrap-box{
height: 200px;
overflow-y: scroll;
}
</style>