使用前端路由,当切换到新路由时,想要页面滚到顶部,或者是保持原先的滚动位置,就像重新加载页面那样。 vue-router 能做到,而且更好,它让你可以自定义路由切换时页面如何滚动。
在router/index.js文件中添加如下代码:
//表示页面跳转的时候,新页面始终是在顶部 scrollBehavior (to, from, savedPosition) { return { x: 0, y: 0 } }
router/index.js
import Vue from 'vue' import Router from 'vue-router' import Home from '@/pages/home/Home' import City from '@/pages/city/City' import Detail from '@/pages/detail/Detail' Vue.use(Router) export default new Router({ routes: [{ path: '/', name: 'Home', component: Home }, { path: '/city', name: 'City', component: City }, { path: '/detail/:id', name: 'Detail', component: Detail }], scrollBehavior (to, from, savedPosition) { return { x: 0, y: 0 } } })