suoutsky / stepping-stone

bug dictionary
1 stars 0 forks source link

document.body.scrollTop总是0的原因(vue中怎么做锚点定位) #9

Open suoutsky opened 6 years ago

suoutsky commented 6 years ago

image image 不能达到想要的效果,跳转到其他页面去了,和vue-router有关。锚点进入前端路由

解决办法

方法一

<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>

其實 vue-router 內部處理跳轉描點的方式是差不多的,只是這裡我們自己來實現。

可以包裝成 mixindirective來達到複用,這裡就不贅述了。

方法二

使用 History 模式


const router = new VueRouter({
  routes,
  mode: 'history',
  scrollBehavior (to, from, savedPosition) {
      // 如果你的連結是帶 # 這種
      // to.hash 就會有值(值就是連結)
      // 例如 #3
      if (to.hash) {
        return {
          // 這個是透過 to.hash 的值來找到對應的元素
          // 照你的 html 來看是不用多加處理這樣就可以了
          // 例如你按下 #3 的連結,就會變成 querySelector('#3'),自然會找到 id = 3 的元素
          selector: to.hash
        }
      }
    }
})