vue回到顶部功能
时间: 2023-06-29 14:16:46 浏览: 46
可以通过以下几种方式实现 Vue 的回到顶部功能:
1. 使用 Vue 插件:可以使用现有的 Vue 插件来实现回到顶部的功能,例如 vue-backtotop、vue-go-top 等。
2. 自定义指令:可以编写一个自定义指令来实现回到顶部的功能,例如:
```javascript
Vue.directive('scroll', {
inserted: function (el, binding) {
let f = function (evt) {
if (binding.value(evt, el)) {
window.scrollTo(0, 0);
}
};
el.__vueScroll__ = f;
window.addEventListener('scroll', f);
},
unbind: function (el) {
window.removeEventListener('scroll', el.__vueScroll__);
el.__vueScroll__ = null;
},
});
```
然后在组件中使用 v-scroll 指令即可。
3. 使用组件:可以编写一个回到顶部的组件,例如:
```javascript
<template>
<div class="back-to-top" v-if="show" @click="scrollTop">
<i class="fa fa-chevron-up"></i>
</div>
</template>
<script>
export default {
data() {
return {
show: false,
};
},
created() {
window.addEventListener('scroll', this.handleScroll);
},
destroyed() {
window.removeEventListener('scroll', this.handleScroll);
},
methods: {
handleScroll() {
this.show = window.pageYOffset > 100;
},
scrollTop() {
window.scrollTo({
top: 0,
behavior: 'smooth',
});
},
},
};
</script>
<style scoped>
.back-to-top {
position: fixed;
bottom: 20px;
right: 20px;
background: #333;
color: #fff;
width: 40px;
height: 40px;
line-height: 40px;
text-align: center;
border-radius: 2px;
cursor: pointer;
transition: opacity 0.2s ease-out;
}
.back-to-top:hover {
opacity: 0.8;
}
</style>
```
然后在需要使用的组件中引入该组件即可。