Vue路由scrollBehavior滾動行為控制錨點


  使用前端路由,當切換到新路由時,想要頁面滾到頂部,或者是保持原先的滾動位置,就像重新加載頁面那樣。 vue-router 能做到,而且更好,它讓你可以自定義路由切換時頁面如何滾動。

  注意: 這個功能只在 HTML5 history 模式下可用。

  當創建一個 Router 實例,你可以提供一個 scrollBehavior 方法:

const router = new VueRouter({ routes: [...], scrollBehavior (to, from, savedPosition) { // return 期望滾動到哪個的位置
 } })

  scrollBehavior 方法接收 to 和 from 路由對象。第三個參數 savedPosition 當且僅當 popstate 導航 (通過瀏覽器的 前進/后退 按鈕觸發) 時才可用。

  這個方法返回滾動位置的對象信息,長這樣:

  • { x: number, y: number }
  • { selector: string, offset? : { x: number, y: number }} (offset 只在 2.6.0+ 支持)

  如果返回一個 falsy (注:falsy 不是 false參考這里)的值,或者是一個空對象,那么不會發生滾動。

  舉例:

scrollBehavior (to, from, savedPosition) { return { x: 0, y: 0 } }

  對於所有路由導航,簡單地讓頁面滾動到頂部。

  返回 savedPosition,在按下 后退/前進 按鈕時,就會像瀏覽器的原生表現那樣:

scrollBehavior (to, from, savedPosition) { if (savedPosition) { return savedPosition } else { return { x: 0, y: 0 } } }

  如果你要模擬『滾動到錨點』的行為:

scrollBehavior (to, from, savedPosition) { if (to.hash) { return { selector: to.hash } } }

  我們還可以利用路由元信息更細顆粒度地控制滾動。查看完整例子:

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 } // 如果meta中有scrollTop
    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 } }

  與keepAlive結合,如果keepAlive的話,保存停留的位置:

scrollBehavior (to, from, savedPosition) { if (savedPosition) { return savedPosition } else { if (from.meta.keepAlive) {   from.meta.savedPosition = document.body.scrollTop; } return { x: 0, y: to.meta.savedPosition ||0} } }

  在無法使用history模式的情況下,使用另外一種方式:

const Foo = { template: ` <div>
            <div><a href="javascript:void(0)" @click="goAnchor('#anchor-'+index)" v-for="index in 20"> {{index}} </a></div>
            <div :id="'anchor-'+index" class="item" v-for="index in 20">{{index}}</div>
        </div> `, methods: { goAnchor(selector) { var anchor = this.$el.querySelector(selector) document.body.scrollTop = anchor.offsetTop } } } const Bar = { template: '<div>bar</div>' } const routes = [ { path: '/foo', component: Foo }, { path: '/bar', component: Bar } ] const router = new VueRouter({ routes, }) const app = new Vue({ router }).$mount('#app')

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM