🐕

Vuejs3 <script setup> 構文 トップに戻るボタン

2022/10/13に公開

templete

<template>
  <transition name="opacity">
    <button 
      v-show="buttonActive"
      @click="pageTop"
      class="fixed right-3 bottom-3 text-white bg-teal-500 w-20 h-20 rounded-full"
    >
      トップに戻る
    </button>
  </transition>
</template>

script

<script setup>
import { onMounted, ref } from 'vue'

const buttonActive = ref(false)

let scroll = 0

const pageTop = () => {
  window.scrollTo({
      top: 0,
      behavior: 'smooth'
  })
}

const scrollWindow = () => {
  const top = 100 //topから100pxスクロールしたらボタン登場
  scroll = window.scrollY //垂直方向

  if (top <= scroll) {
    buttonActive.value = true
  } else {
    buttonActive.value = false
  }
}

onMounted(() => {
  window.addEventListener('scroll', scrollWindow)
})
</script>

アニメーション

動きが欲しい人用

<style scoped>
.opacity-enter{
  opacity: 0;
}
.opacity-enter-active{
  transition: opacity 1s;
}
.opacity-enter-to{
  opacity: 1;
}
.opacity-leave{
  opacity: 1;
}
.opacity-leave-active{
  transition: opacity 1s;
}
.opacity-leave-to{
  opacity: 0;
}
</style>

完成イメージ

参考サイト

https://qiita.com/TK-C/items/42b25ff4ec56528ad870

Discussion