Nuxtのページスクロールを拡張機能なしで実装した話

今回は Nuxt.js のページスクロールをライブラリなしで実装した話です。

一般的にページスクロールを入れようと考えると、ライブラリを入れて動かすのがメジャーっぽいですが、今回ライブラリなしで作っちゃえ!と思い、作ってみた次第ですw

参考としてはコチラの Qiita の記事。

こちらでTOPに戻るやり方を紹介していたので、これを素に id で指定したタグのところに動くギミックを実装できないかと考えました。

<template>
  <div class="container">
    <div class="nav">
      <a href="#fast" @click="returnScroll(1)"><p>1へ飛ぶ</p></a>
      <a href="#second" @click="returnScroll(2)"><p>2へ飛ぶ</p></a>
      <a href="#third" @click="returnScroll(3)"><p>3へ飛ぶ</p></a>
      <a href="#four" @click="returnScroll(4)"><p>4へ飛ぶ</p></a>
      <a href="#five" @click="returnScroll(5)"><p>5へ飛ぶ</p></a>
    </div>




    <!-- idをrefとして指定してる点に注意↓ -->




    <div class="test" ref="fast">Hello world1</div>
    <div class="test" ref="second">Hello world2</div>
    <div class="test" ref="third">Hello world3</div>
    <div class="test" ref="four">Hello world4</div>
    <div class="test" ref="five">Hello world5</div>
    <button @click="returnScroll(6)">TOPに戻る</button>
  </div>
</template>
<script>
export default {
  data(){
    return{
      fastDiv: '',
      secondDiv: '',
      thirdDiv: '',
      fourDiv: '',
      fiveDiv: '',
    }
  },
  mounted(){
    this.fastDiv = this.$refs.fast.getBoundingClientRect()
    this.secondDiv = this.$refs.second.getBoundingClientRect()
    this.thirdDiv = this.$refs.third.getBoundingClientRect()
    this.fourDiv = this.$refs.ford.getBoundingClientRect()
    this.fiveDiv = this.$refs.five.getBoundingClientRect()
  },
  methods: {
    returnScroll(value) {
      if(value == 1){
        window.scrollTo({
          top: this.fastDiv.y,
          behavior: 'smooth'
        })
      } else if(value == 2){
        window.scrollTo({
          top: this.secondDiv.y,
          behavior: 'smooth'
        })
      } else if(value == 3){
        window.scrollTo({
          top: this.thirdDiv.y,
          behavior: 'smooth'
        })
      } else if(value == 4){
        window.scrollTo({
          top: this.fourDiv.y,
          behavior: 'smooth'
        })
      } else if(value == 5){
        window.scrollTo({
          top: this.fiveDiv.y,
          behavior: 'smooth'
        })
      } else if(value == 6){
        window.scrollTo({
          top: 0,
          behavior: 'smooth'
        })
      }
    }
  }
}
</script>
<style scoped>
.container {
  text-align: center;
}
.nav{
  display: block;
}
.test {
  margin: 30px;
  height: 50vh;
  background: pink;
  font-size: 40px;
}
</style>
で、いきなりですが、完成したのが↑これ。
(スタイルはサンプルコードなので見やすく作ってあるだけです)
引数でタグの id 要素を指定して、getBoundingClientRect() で高さを取得して動く様にしてます。
なんかもうちょっと綺麗にまとまらないのかと思うんですが、まあ、こんな感じでできるよって事でw

コメント

タイトルとURLをコピーしました