开发uniapp的时候难免会用到一些自定义的东西,就比如自定义排序。然是小程序不像PC端有DOM所以一时间无法下手。刚好看了文档里面有一个<movable-area>标签可以完美的实现我们的需求。那么让我们开始一步步实现吧
效果图
1. 这里的每一个标签属性可以看文档了解movable-view | uni-app官网
<template>
<view class="content">
<movable-area :animation="animation" :direction="direction">
<movable-view>
</movable-view>
</movable-area>
</view>
</template>
<script>
export default {
props: {
//一行展示几列
column: {
type: Number,
default: 1
},
//渲染的数组
value: {
type: Array,
default: () => []
},
width: {
type: String,
default: '100%'
},
height: {
type: String,
default: 'auto'
},
//唯一标识
itemKey: {
type: String,
required: true
},
itemHeight: {
type: String,
default: '60px'
},
direction: {
type: String,
default: 'all',
validator: value => {
return ['all', 'vertical', 'horizontal', 'none'].includes(value);
}
},
animation: {
type: Boolean,
default: true
},
damping: {
type: Number,
default: 20
},
longpress: {
type: Boolean,
default: true
},
},
data() {
return {
disabled: true,
activeIndex: -1,//点击的当前行
moveToIndex: -1,//后期用来判断移动到第几行
oldIndex: -1,//初始行
tempDragInfo: { //这里用来保存移动的X,Y
x: '',
y: ''
},
cloneList: [],//备份列表数据
}
},
methods: {
}
}
</script>
<style lang="scss">
</style>
前期工作我们都准备好了,接下来我们开始第一步 如何给拖拽区域设置宽高
2.这里我们直接按照设备的屏幕宽度去百分比设置,然后给移动区域设置样式
<template>
<view class="content">
<movable-area :style="[getAreaStyle]">
<movable-view :animation="animation" :direction="direction
:damping="damping" :style="[getViewStyle]">
</movable-view>
</movable-area>
</view>
</template>
computed: {
getAreaStyle() {
const width = this.getRealWidth(this.width);
return {
width: width + 'px',
height: this.height !== 'auto' ? this.height : Math.round(this.list.length / this.column) * this
.getItemHeight + 'px'
};
},
getViewStyle() {
const {
itemHeight,
getItemWidth
} = this;
return {
width: getItemWidth + 'px',
height: itemHeight
};
},
getItemHeight() {
return parseFloat(this.itemHeight);
},
getItemWidth() {
if (this.column === 0) return;
const width = this.getRealWidth(this.width);
return (parseFloat(width) / this.column).toFixed(2);
},
},
3.接下来是我们数据初始化,我们要循环数组添加X,Y坐标