如果頁面A沿Y軸滾動一段距離,然後跳轉到頁面B;在進入B頁面時,B頁面已經滾動到頁面A的距離,返回頁面A,發現A還在之前的滾動位置;
- 在路由守衛回調中,設置每次進入路由時,將window的scroll值設置爲0;window.scroll(0,0);
// 全局路由守衛
router.beforeEach((to, from, next) => {
// to: Route: 即將要進入的目標 路由對象
// from: Route: 當前導航正要離開的路由
// next: Function: 一定要調用該方法來 resolve 這個鉤子。執行效果依賴 next 方法的調用參數。
// A跳轉到B,B頁面停留在A頁面的滾動位置;解決方法:將scrollTop設置爲0
window.scroll(0, 0);
// nextRoute: 設置需要路由守衛的路由集合
const nextRoute = ['home', 'good-list', 'good-detail', 'cart', 'profile'];
let isLogin = global.isLogin; // 是否登錄
// 未登錄狀態;當路由到nextRoute指定頁時,跳轉至login
if (nextRoute.indexOf(to.name) >= 0) {
if (!isLogin) {
console.log('what fuck');
router.push({ name: 'login' })
}
}
// 已登錄狀態;當路由到login時,跳轉至home
if (to.name === 'login') {
if (isLogin) {
router.push({ name: 'home' });
}
}
next();
});