写段vue封装下拉刷新的代码
时间: 2023-05-14 20:04:36 浏览: 122
非常感谢您的提问,以下是一个简单的 Vue 下拉刷新组件的封装代码:
```vue
<template>
<div ref="wrapper" class="wrapper">
<div ref="scroller" class="scroller">
<slot></slot>
</div>
<div v-show="showTopTip" class="top-tip">{{ topTipText }}</div>
<div v-show="showBottomTip" class="bottom-tip">{{ bottomTipText }}</div>
</div>
</template>
<script>
export default {
name: 'PullRefresh',
props: {
topTipText: {
type: String,
default: '下拉刷新'
},
bottomTipText: {
type: String,
default: '上拉加载更多'
},
threshold: {
type: Number,
default: 50
}
},
data() {
return {
startY: 0,
endY: 0,
isDragging: false,
isRefreshing: false,
isLoadingMore: false,
showTopTip: false,
showBottomTip: false
}
},
mounted() {
this.$nextTick(() => {
this.initScroll()
})
},
methods: {
initScroll() {
const wrapper = this.$refs.wrapper
const scroller = this.$refs.scroller
let startY = 0
let endY = 0
let isDragging = false
wrapper.addEventListener('touchstart', e => {
startY = e.touches[0].pageY
isDragging = true
})
wrapper.addEventListener('touchmove', e => {
if (!isDragging) {
return
}
endY = e.touches[0].pageY
if (endY - startY > 0) {
// 下拉刷新
e.preventDefault()
if (!this.isRefreshing) {
this.showTopTip = endY - startY > this.threshold
}
if (this.showTopTip) {
scroller.style.transform = `translate3d(0, ${endY - startY}px, 0)`
}
} else {
// 上拉加载更多
const wrapperHeight = wrapper.clientHeight
const scrollerHeight = scroller.clientHeight
const scrollTop = wrapper.scrollTop
if (scrollTop + wrapperHeight >= scrollerHeight) {
e.preventDefault()
if (!this.isLoadingMore) {
this.showBottomTip = true
}
}
}
})
wrapper.addEventListener('touchend', e => {
if (this.showTopTip) {
this.isRefreshing = true
this.showTopTip = false
scroller.style.transition = 'transform 0.3s ease-in-out'
scroller.style.transform = `translate3d(0, ${this.threshold}px, 0)`
setTimeout(() => {
this.$emit('refresh')
this.isRefreshing = false
scroller.style.transition = 'none'
scroller.style.transform = 'none'
}, 1000)
} else if (this.showBottomTip) {
this.isLoadingMore = true
this.showBottomTip = false
this.$emit('load-more')
setTimeout(() => {
this.isLoadingMore = false
}, 1000)
}
isDragging = false
})
}
}
}
</script>
<style scoped>
.wrapper {
overflow: hidden;
position: relative;
}
.scroller {
position: relative;
transform: translate3d(0, 0, 0);
transition: transform 0.3s ease-in-out;
}
.top-tip,
.bottom-tip {
position: absolute;
left: 0;
right: 0;
text-align: center;
font-size: 14px;
line-height: 40px;
color: #999;
}
.top-tip {
top: -40px;
}
.bottom-tip {
bottom: -40px;
}
</style>
```
这个组件可以通过 `threshold` 属性来设置下拉刷新的阈值,通过 `topTipText` 和 `bottomTipText` 属性来设置顶部和底部提示文字。在下拉刷新时,会触发 `refresh` 事件;在上拉加载更多时,会触发 `load-more` 事件。
阅读全文