@peccul is peccu

(love peccu '(emacs lisp cat outdoor bicycle mac linux coffee))

Vue.js+VueRouterを使っているときに#idでページ内を移動する

vue routerを使っているとページを示すために #/route が利用されているので、aタグやrouter-linkでidへスクロールするリンクが作成できない。 (そのidに対応するページをvue routerが探してしまう)

そこでvue routerの持つルーティング情報を監視してJSでスクロールさせる方法を取り入れてみると ページ内の指定したidのついた要素までスクロールさせることがでた。

  • vueファイルの例
<template>
  <div id="top">
    <router-link to="#bottom">scroll to bottom</router-link>
    <div style="height: 2000px;"></div>
    <router-link to="#top" id="bottom">scroll to top</router-link>
  </div>
</template>

<script>
export default {
  watch: {
    '$route': function (n, o) {
      if (n.hash.match(/^#/)) {
        document.getElementById(n.hash.replace(/^#/, '')).scrollIntoView()
      }
      console.log('new, old', [n.hash, o.hash])
    }
  },
  mounted () {
    if (this.$route.hash.match(/^#/)) {
      document.getElementById(this.$route.hash.replace(/^#/, '')).scrollIntoView()
    }
  }
}
</script>
  • jsfiddleでの例

参考URL