vue-router跳转滚动的问题(scrollBehavior)

使用前端路由,当切换到新路由时,想要页面滚到顶部,或者是保持原先的滚动位置,就像重新加载页面那样。这个功能只在支持 history.pushState 的浏览器中可用。

1. 最简单的方法:scrollBehavior

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

` } const scrollBehavior = (to, from, savedPosition) => { if (savedPosition) {//返回之前的原位置 // savedPosition 当且仅当 popstate 导航 (通过浏览器的 前进/后退 按钮触发) 时才可用。 return savedPosition } else { const position = {} if (to.hash) {//如果路径中有哈希值,就采用锚点定位 position.selector = to.hash } if (to.matched.some(m => m.meta.scrollToTop)) {//如果路由元信息中存在参数,对参数做进一步判断(此示例代表滚动到顶部) position.x = 0 position.y = 0 } //如果返回一个 falsy (假的值),或者是一个空对象,那么不会发生滚动。 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')

跳转回原来页面的位置,需要记住之前的位置。

1.路由跳转后用keep-alive记住状态 返回上次滚动的位置
keep-alive 会缓存当前的视图,配合路由元信息meta来做判断,用v-if显示不同的


   

 
-------------------------------------------------------------------------------
routes=[
  {path:'/home',component:Home,meta:{keepAlive:true}},
  {path:'/login',component:Login,meta:{keepAlive:false}}
]

2.sessionStorage记录位置
3.用vuex纪录位置

你可能感兴趣的:(vue-router跳转滚动的问题(scrollBehavior))