第一種:使用vue-router
history 模式下,用scrollBehavior 方法實現。
1 export default new Router({ 2 mode: 'history', 3 routes: routeArray, 4 scrollBehavior (to, from, savedPosition) { 5 return { x: 0, y: 0 } 6 } 7 });
第二種:滾動條在非body上
示例:
1 <template> 2 <!--.wrap-box元素固定高度,內容溢出時,該元素縱向滾動--> 3 <div class="wrap-box" ref="scollElement"> 4 <!--.box元素超出父元素.wrap-box高度時,頁面會出現滾動條(滾動元素為.wrap-box)--> 5 <div class="box"> 6 <!--內容區(切換不同模塊)--> 7 <router-view></router-view> 8 </div> 9 </div> 10 </template> 11 12 <script> 13 export default{ 14 name:'warp-box', 15 updated () { // 切換不同模塊時觸發 16 this.$nextTick(()=>{ 17 if(this.$refs.scollElement){ // 滾動元素跳轉到頂部 18 this.$refs.scollElement.scrollTop = 0; 19 } 20 }) 21 } 22 } 23 </script> 24 25 <style> 26 .wrap-box{ 27 height: 200px; 28 overflow-y: scroll; 29 } 30 </style>
第三種:基於第二種
在模塊化開發中,子模塊存在翻頁按鈕,當頁碼切換時回到頂部。(此時的滾動元素在祖先模塊中)
1 <template> 2 <div class="item-one" ref="itemOne"> 3 <div class="list-box"> 4 5 </div> 6 <div class="page-box"> 7 <el-pagination 8 @current-change="handleCurrentChange" 9 :current-page="currentPage" 10 :page-size="pageSize" 11 layout="total, sizes, prev, pager, next, jumper" 12 :total="total"> 13 </el-pagination> 14 </div> 15 </div> 16 </template> 17 18 <script> 19 export default { 20 name:'item-one', 21 data(){ 22 return{ 23 total:0, 24 tableData:[], 25 pageSize:20, 26 currentPage:1, 27 } 28 }, 29 methods:{ 30 initData(){//初始化數據 31 // 初始化數據 total、tableData、pageSize、currentPage等 32 }, 33 handleCurrentChange(currentPage){ // currentPage 改變時會觸發 34 this.currentPage = currentPage; 35 this.initData(); 36 /* 37 1、當前模塊為子模塊,當前模塊中內容溢出時存在滾動條,滾動條在祖先模塊中。 38 2、當進行翻頁時,路由沒有變化,無法使用路由跳轉滾動條回到頂部的設置, 39 並且滾動條並不在body上。 40 3、解決方法:在子模塊中找到祖先模塊中的滾動元素。(使用$refs的屬性offsetParent尋找滾動元素) 41 4、this.$el為當前組件的掛載元素(這里可以等同於this.$refs.itemOne) 42 */ 43 // console.log(this.$el.offsetParent.offsetParent,'滾動元素'); 44 this.$nextTick(()=>{ 45 this.$el.offsetParent.scrollTop = 0; 46 //this.$el.offsetParent 僅限於當前示例模塊的祖先模塊基於方法二(一層模塊嵌套) 47 //祖先模塊的層次將決定offsetParent的獲取,使用時應在控制台打印出,確認后使用 48 }); 49 }, 50 } 51 } 52 </script> 53 54 <style> 55 </style>
