uniapp实现像qq消息列表左滑显示右侧操作栏效果
先看效果图
代码
SlidableChatEntry.vue
<template><!-- 聊天项列表 --><view class="chat-item"@touchstart="handleTouchStart($event)"@touchmove="handleTouchMove($event)"@touchend="handleTouchEnd()"><!-- 聊天内容区域 --><view class="chat-content":style="getContentStyle()"><slot name="content"></slot></view><!-- 操作按钮区域 --><view class="action-buttons":style="getButtonStyle()"@click.stop="handleAction()"><slot name="menu"></slot></view></view>
</template>
<script>
export default {data() {return {chatList: [],// 记录每个聊天项的滑动状态swipeStates: [], // 存储每个聊天项的滑动距离touchStartXs: [] // 记录每个聊天项的触摸起始位置}},created() {// 初始化数组this.chatList.forEach(() => {this.swipeStates.push()this.touchStartXs.push()})},methods: {// 触摸开始事件handleTouchStart(e) {this.touchStartXs = e.touches[0].clientX},// 触摸移动事件handleTouchMove(e, index) {const touchX = e.touches[0].clientXlet deltaX = touchX - this.touchStartXs// 限制只能向左滑动(禁止向右滑动超过初始位置)if (deltaX > 0) {deltaX = 0}// 限制最大滑动距离为按钮总宽度(约150px)if (deltaX < -150) {deltaX = -150}this.swipeStates = deltaX},// 触摸结束事件handleTouchEnd() {// 如果滑动距离超过阈值(50px),则完全滑出按钮if (this.swipeStates < -50) {this.swipeStates = -150 // 完全滑出} else {// 否则恢复原状this.swipeStates = 0}},//恢复原状closeSwipe(){this.swipeStates = 0},// 获取内容区域样式getContentStyle() {return {transform: `translateX(${this.swipeStates}px)`}},// 获取按钮区域样式getButtonStyle() {return {transform: `translateX(${this.swipeStates + 150}px)` // 初始位置在屏幕外(150px)}},// 处理操作按钮点击handleAction() {}}
}
</script>
<style scoped>.chat-item {position: relative;overflow: hidden; /* 防止按钮溢出 */box-sizing: border-box;
}/* 聊天内容区域 */
.chat-content {display: flex;align-items: center;flex: 1;z-index: 2; /* 确保内容在按钮上方 */transition: transform 0.3s ease;
}/* 操作按钮区域 */
.action-buttons {position: absolute;right: 0;top: 0;bottom: 0;z-index: 1; /* 按钮在内容下方 */transition: transform 0.3s ease;
}
</style>
使用
组件引用
<SlidableChatEntry><template v-slot:content>//在这里写你的具体内容</template><template v-slot:menu>//在这里写你的按钮</template>
</SlidableChatEntry >
组件导入
import SlidableChatEntry from '@/components/SlidableChatEntry.vue'
export default {components: {SlidableChatEntry }
}
样式完全自己掌控,此组件套上去不会改变被套元素的原有样式