在vue项目中,有些页面需要toTop的按钮(滚到顶部),因此在页面中需要用到滚动事件,但是如果很多页面都需要用到这个按钮,就要在这些页面中都加上滚动事件,会导致页面代码臃肿,不便维护。
这里使用vue自定义指令封装一个全局的滚动事件,在需要的页面引用组件,加上指令即可。
下面上代码:
1、首先封装一个toTop的按钮组件(默认显示)
<template>
<div id="toTop" class="iconfont icon-dingbu" @click="toTop"></div>
</template>
<script>
export default {
name: 'toTop1',
props: {
doc: {
default: null,
type: String
}
},
methods: {
toTop(){
document.querySelector(this.doc).scrollTop = 0
}
}
}
</script>
<style scoped>
#toTop {
width: 40px;
text-align: center;
font-size: 22px;
line-height: 40px;
border-radius: 50%;
position: fixed;
right: 20px;
top: 80%;
color: #fff;
background: rgba(246, 152, 5, .7);
z-index: