vue项目中在使用vue-router切换页面的时候滚动条怎样自动滚动到顶部?

完整代码例子:

import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const Home = { template: '
home
' } const Foo = { template: '
foo
' } const Bar = { template: `
bar

Anchor

` } // scrollBehavior: // - only available in html5 history mode // - defaults to no scroll behavior // - return false to prevent scroll const scrollBehavior = (to, from, savedPosition) => { if (savedPosition) { // savedPosition is only available for popstate navigations. return savedPosition } else { const position = {} // new navigation. // scroll to anchor by returning the selector if (to.hash) { position.selector = to.hash } // check if any matched route config has meta that requires scrolling to top if (to.matched.some(m => m.meta.scrollToTop)) { // cords will be used if no selector is provided, // or if the selector didn't match any element. position.x = 0 position.y = 0 } // if the returned position is falsy or an empty object, // will retain current scroll position. return position } } const router = new VueRouter({ mode: 'history', base: __dirname, scrollBehavior, routes: [ { path: '/', component: Home, meta: { scrollToTop: true }}, { path: '/foo', component: Foo }, { path: '/bar', component: Bar, meta: { scrollToTop: true }} ] }) new Vue({ router, template: `

Scroll Behavior

  • /
  • /foo
  • /bar
  • /bar#anchor
` }).$mount('#app')

在网上查了一下,网友说还可以试试在main.js入口文件配合vue-router写这个

router.afterEach((to,from,next) => {
    window.scrollTo(0,0);
});

你可能感兴趣的:(router)