跳转到内容

❧ 滑动连续选择示例

<template>
<div class="box">
<div v-for="(item, index) of list" class="card" :class="{active: item.checked}" @mousedown="addEvent(item, index)" @mouseover="moveEvent(index)" @mouseup="removeEvent()">
<input name="0" type="checkbox" :checked="item.checked"/>
测试连续选择{{index}}
</div>
</div>
</template>
<script lang="ts">
import { ref, defineComponent, Ref } from 'vue'
export default defineComponent({
name: 'swipe select',
setup: () => {
const list: Ref<{[key: string]: any}[]> = ref([]);
// 测试数据
for (let i=0;i<100;i++) {
list.value.push({checked:false});
}
const startIndex = ref(0); // 开始索引
const isReady = ref(false); // 是否正在连选
// 鼠标滑动事件
const moveEvent = (index: number) => {
if (!isReady.value) {
return;
}
for (const item of list.value) {
item.checked = false;
}
const sign = index > startIndex.value ? 1 : -1;
let count = startIndex.value;
const endIndex = index + sign;
while(count != endIndex) {
list.value[count].checked = true;
count += sign;
}
}
// 鼠标按下去绑定onmouseover监听
const addEvent = (item: any, index: number) => {
isReady.value = true;
const {checked} = item;
startIndex.value = index;
item.checked = !checked;
}
// 鼠标松开解绑onmouseover监听
const removeEvent = () => {
isReady.value = false;
}
return {
list,
addEvent,
removeEvent,
moveEvent,
}
}
})
</script>
<style scoped>
.box {
width: 500px;
margin: 0 auto;
}
.card {
border: 1px solid #ccc;
margin: 10px 0;
padding: 10px;
user-select: none;
text-align: left;
}
.card.active {
background-color: #c6d9f5;
}
</style>