利用uni-app在移动端实现拖拉拽排序功能(存在BUG 真机中无法运行)
drag-demo.vue
<template>
<view class="drag-demo">
<u--text text="移动端拖拉拽排序demo"> </u--text>
<u--text text="基于Vue3+ uni-app + u-view-plus"> </u--text>
<view class="drag-list" ref="drag-list">
<view class="block" ref="block-ref" v-for="item in 6" style="background-color: pink;" @touchstart="onTouchStart" @touchmove="onTouchMove" @touchend="onTouchEnd($event,index)">{{item}}</view>
<view ref="frosted"></view>
</view>
</view>
</template>
<script setup>
import {ref, reactive, getCurrentInstance, onMounted} from "vue"
const { proxy } = getCurrentInstance();
let timer;
let choice = false;
const onTouchStart = (e) => {
console.log('onTouchStart',e);
const frosted = proxy.$refs['frosted'].$el;
const width = e.instance.$el.clientWidth;
const height = e.instance.$el.clientHeight;
console.log(width, height);
timer = setTimeout(() => {
frosted.classList.add('frosted')
e.instance.$el.classList.add('select');
choice = true;
}, 500);
};
const onTouchMove = (e) => {
e.preventDefault();
console.log('onTouchMove',e);
const frosted = proxy.$refs['frosted'].$el;
clearTimeout(timer);
frosted.classList.remove('frosted');
e.instance.$el.classList.remove('select');
timer = 0;
}
const onTouchEnd = (event) => {
console.log('onTouchEnd', event);
const width = event.instance.$el.clientWidth;
const height = event.instance.$el.clientHeight;
clearTimeout(timer);
if(timer != 0) {
console.log('不是长按')
}
if(choice) {
const all = proxy.$refs['drag-list'].$el;
const block = all.children;
const distance = proxy.$refs['drag-list'].$el.offsetTop;
const positionY = event.changedTouches[0].clientY;
const positionX = event.changedTouches[0].clientX;
const line = Math.trunc(Math.abs(positionY - distance) / height);
const column = Math.trunc(positionX / width) + 1;
const num = line * 2 + column;
const choiceNode = event.instance.$el;
all.removeChild(choiceNode);
all.insertBefore(choiceNode, block[num - 1])
}
}
onMounted(()=>{
})
</script>
<style lang="scss" scoped>
.drag-demo{
height: 90vh;
.drag-list{
width: 100%;
display: flex;
flex-wrap: wrap;
position: relative;
.block{
width: calc(50% - 20rpx);
height: 200rpx;
margin: 20rpx 10rpx 20rpx 10rpx;
z-index: 1;
}
.select {
position: relative;
z-index: 99;
}
.frosted {
width: 100%;
height: 100%;
position: absolute;
background-color: rgba(56,50,50,0.1);
backdrop-filter: blur(5px);
z-index: 10;
}
}
}
</style>