MST
星途 面试题库

面试题:Vue Router中如何解决路由切换时页面滚动位置不重置的问题

在Vue项目中使用Vue Router进行页面导航时,有时会遇到路由切换后页面滚动位置保持不变的情况。请阐述你会如何通过Vue Router的相关配置或生命周期钩子函数来解决这个问题,使每次路由切换时页面滚动位置重置到顶部或特定位置。
30.3万 热度难度
前端开发Vue

知识考点

AI 面试

面试题答案

一键面试
  1. 使用router.afterEach全局后置钩子函数
    • router/index.js文件中,通过router.afterEach钩子函数来重置页面滚动位置。
    import Vue from 'vue';
    import Router from 'vue-router';
    import Home from '@/components/Home';
    
    Vue.use(Router);
    
    const router = new Router({
      routes: [
        {
          path: '/',
          name: 'Home',
          component: Home
        }
      ]
    });
    
    router.afterEach((to, from, next) => {
      window.scrollTo(0, 0); // 重置滚动位置到顶部
      next();
    });
    
    export default router;
    
  2. router-view上使用v - scroll - to指令(需要自定义指令)
    • 首先定义一个自定义指令v - scroll - to
    Vue.directive('scroll - to', {
      inserted: function (el) {
        el.scrollTop = 0;
      }
    });
    
    • 然后在App.vue中的router - view上使用该指令。
    <template>
      <div id="app">
        <router - view v - scroll - to></router - view>
      </div>
    </template>
    
    <script>
    export default {
      name: 'App'
    };
    </script>
    
    <style>
    #app {
      font - family: Avenir, Helvetica, Arial, sans - serif;
      -webkit - font - smoothing: antialiased;
      -moz - osx - font - smoothing: grayscale;
      text - align: center;
      color: #2c3e50;
      margin - top: 60px;
    }
    </style>
    
  3. 利用路由元信息(meta)和组件生命周期钩子
    • 在路由配置中设置meta字段,标记需要重置滚动位置的路由。
    const router = new Router({
      routes: [
        {
          path: '/home',
          name: 'Home',
          component: Home,
          meta: {
            scrollToTop: true
          }
        }
      ]
    });
    
    • 在组件的activated生命周期钩子函数中根据meta信息重置滚动位置。
    <template>
      <div>
        <!-- 组件内容 -->
      </div>
    </template>
    
    <script>
    export default {
      activated() {
        if (this.$route.meta.scrollToTop) {
          window.scrollTo(0, 0);
        }
      }
    };
    </script>