JSFiddle - React, Tailwind, and code Playground
by tema1302
HTML
<div id="button-anchor">
<button-up></button-up>
</div>
JavaScript
Vue.component('button-up', {
template: '<a v-bind:class="{ visible: userScrollTop }" v-on:click="moveUp()"><i class="fa fa-arrow-circle-up" ></i>{{userScrollTop}}</a>',
data: function(){
return {
userScrollTop: Boolean,
previousScrollPosition: 0
}
},
methods: {
moveUp() {
window.scrollTo({
left: 0,
top: 0,
behavior: 'smooth'
})
},
appearButton(event) {
//вычисляем текущее положение скролла и сравниваем его с предыдущим
let currentScrollPosition = window.scrollY;
if (currentScrollPosition < this.previousScrollPosition) {
this.userScrollTop = true;
console.log('up')
} else {
this.userScrollTop = false;
console.log('down')
}
//И если юзер наверху страницы, скрываем элемент
if (currentScrollPosition == 0) {
this.userScrollTop = false;
}
this.previousScrollPosition = currentScrollPosition;
}
},
mounted() {
window.addEventListener('scroll', this.appearButton);
},
beforeDestroy() {
window.removeEventListener('scroll', this.appearButton);
}
})
new Vue({
el: '#button-anchor'
})