面试题答案
一键面试- 使用
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;
- 在
- 在
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>
- 首先定义一个自定义指令
- 利用路由元信息(
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>
- 在路由配置中设置