vite+vue3路由切換滾動條位置重置
當(dāng)切換到新路由時,想要頁面滾到頂部,或者是保持原先的滾動位置,就像重新加載頁面那樣,vue-router
可以自定義路由切換時頁面如何滾動
使用原生滾動條
VueRouter官方文檔:https://router.vuejs.org/zh/guide/advanced/scroll-behavior.html
為 Router
實例提供一個 scrollBehavior
方法,接收 to
和 from
路由對象
import { createRouter, createWebHashHistory, createWebHistory, RouteRecordRaw } from 'vue-router'
const routes: Array<RouteRecordRaw> = [
{
path: '/',
name: '...',
component: () => import('@/views/xxx.vue')
},
]
const router = createRouter({
history: createWebHashHistory(),
routes,
scrollBehavior(to, from, savedPosition) {
// 始終滾動到頂部
return { top: 0 }
}
})
export default router

使用el-scrollbar
el-scrollbar使用手冊:https://element-plus.org/zh-CN/component/scrollbar.html
路由切換時因為 el-scrollbar
組件包裹著router-view
,所以頁面切換時滾動條不會置頂,所以需要重置滾動條文章來源:http://www.zghlxwxcb.cn/news/detail-733727.html
<el-scrollbar>
<RouterView></RouterView>
</el-scrollbar>
- el-scrollbar方法
函數(shù) | 解釋 |
---|---|
handleScroll | 觸發(fā)滾動事件 |
scrollTo | 滾動到一組特定坐標(biāo) |
setScrollTop | 設(shè)置滾動條到頂部的距離 |
setScrollLeft | 設(shè)置滾動條到左邊的距離 |
update | 手動更新滾動條狀態(tài) |
wrapRef | 滾動條包裹的 ref 對象 |
<template>
<el-scrollbar ref="scrollContainer">
<router-view />
</el-scrollbar>
</template>
<script setup lang="ts">
import { useRouter } from "vue-router";
const scrollContainer = ref(null);
const router = useRouter();
const handleRouteChange = () => {
if (scrollContainer.value && scrollContainer.value.scrollTo) {
scrollContainer.value.scrollTo(0, 0); // 滾動到頂部
}
};
// 解決:切換頁面,滾動條位置不動
onMounted(() => {
router.afterEach(handleRouteChange);
});
onBeforeUnmount(() => {});
也可以使用EventBus
,每次切換路由時觸發(fā)handleRouteChange
函數(shù)來調(diào)整el-scrollbar
的位置文章來源地址http://www.zghlxwxcb.cn/news/detail-733727.html

useRoute和useRouter
-
useRoute
相當(dāng)于this.$route
,返回當(dāng)前的路由地址 -
useRouter
相當(dāng)于this.$router
,返回路由器實例
import { useRoute } from "vue-router";
const route = useRoute();
console.log(route)

import { useRouter } from "vue-router";
const router = useRouter();
console.log(router)

到了這里,關(guān)于vite+vue3路由切換滾動條位置重置el-scrollbar的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!