ライブラリを使わずにVue.jsでトップへ戻るボタンを実装する方法
 
                            Vue.jsには、vue-scrollのようなsmooth scrollを実装してくれる便利なライブラリがあるのですが、今回はあえてそういったライブラリを使わずにトップへ戻るボタンを実装する方法をご紹介します。
DEMO
See the Pen Vue.js – Scroll Back To Top Button Without Library by mizusawa (@webty_mizusawa) on CodePen.
ソースコード
app.js
window.Vue = require('vue');
Vue.component('pagetop-component', require('./components/PagetopComponent.vue').default);
const app = new Vue({
    el: '#app',
});sample.html
<div id="app" v-cloak>
    <pagetop-component></pagetop-component>
</div>PagetopComponent.vue
<template>
    <transition name="fade">
        <div id="pagetop" class="fixed right-0 bottom-0" v-show="scY > 300" @click="toTop">
            <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none"
                 stroke="#4a5568"
                 stroke-width="1" stroke-linecap="square" stroke-linejoin="arcs">
                <path d="M18 15l-6-6-6 6"/>
            </svg>
        </div>
    </transition>
</template>
<script>
    export default {
        name: "PagetopComponent",
        data() {
            return {
                scTimer: 0,
                scY: 0,
            }
        },
        mounted() {
            window.addEventListener('scroll', this.handleScroll);
        },
        methods: {
            handleScroll: function () {
                if (this.scTimer) return;
                this.scTimer = setTimeout(() => {
                    this.scY = window.scrollY;
                    clearTimeout(this.scTimer);
                    this.scTimer = 0;
                }, 100);
            },
            toTop: function () {
                window.scrollTo({
                    top: 0,
                    behavior: "smooth"
                });
            },
        },
    }
</script>
フェードインの実装
スクロールのハンドリングは、コンポーネントがマウントされたときにイベントを登録してあげることで出来ます。
mounted() {
    window.addEventListener('scroll', this.handleScroll);
},そして、要素の表示・非表示の切り替えはv-showで指定してあげることが出来ます。
また、このとき<transition name="fade"></transition>で囲ってあげることで、要素の表示切り替え時にフェードイン・フェードアウトするようになります。
<transition name="fade">
    <div v-show="scY > 300"></div>
</transition>スムーズスクロールの実装
画面のスクロールはwindow.scrollTo()で実装する事ができます。
window.scrollTo({
    top: 0,
    behavior: "smooth"
});今回は、TOPに戻るだけなので、スクロール位置が0で固定ですが、DOMから対象要素の上側の位置を取得すればページ内スクロールも実装できます。
おわりに
Vue.jsでも簡単にトップへ戻るボタンを実装することは出来ます。
ただ、window.scrollTo()はまだ非対応ブラウザがあるのでpolyfill対応してあげる必要があるでしょう。
