vue3 ts 拖动选择
时间: 2023-09-15 19:17:54 浏览: 60
你可以使用 Vue3 和 TypeScript 实现拖动选择的功能,具体实现方法如下:
1. 在模板中添加一个容器元素,用于包裹需要选择的元素。
2. 在容器元素上绑定 mousedown、mousemove 和 mouseup 事件,分别对应鼠标按下、移动和松开的操作。
3. 在 mousedown 事件处理函数中,记录鼠标按下时的坐标,并设置一个标志位,表示开始选择。
4. 在 mousemove 事件处理函数中,判断标志位是否为真,如果是,则计算鼠标移动的距离,并实时更新选择框的位置和大小。
5. 在 mouseup 事件处理函数中,清除标志位,并根据选择框的位置和大小计算出选择的元素。
6. 将选择的元素保存到组件的数据中,并在模板中渲染出来。
下面是一个简单的示例代码:
```html
<template>
<div class="container"
@mousedown="handleMouseDown"
@mousemove="handleMouseMove"
@mouseup="handleMouseUp">
<div class="item"
v-for="(item, index) in items"
:key="index"
:class="{ selected: selectedItems.includes(item) }">
{{ item }}
</div>
<div class="selection-box" ref="selectionBox"></div>
</div>
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue';
export default defineComponent({
data() {
return {
items: ['item1', 'item2', 'item3', 'item4', 'item5'],
selectedItems: [] as string[],
isSelecting: false,
startX: 0,
startY: 0,
endX: 0,
endY: 0,
};
},
methods: {
handleMouseDown(evt: MouseEvent) {
this.startX = evt.pageX;
this.startY = evt.pageY;
this.endX = evt.pageX;
this.endY = evt.pageY;
this.isSelecting = true;
const selectionBox = this.$refs.selectionBox as HTMLElement;
selectionBox.style.display = 'block';
selectionBox.style.left = `${evt.pageX}px`;
selectionBox.style.top = `${evt.pageY}px`;
selectionBox.style.width = '0';
selectionBox.style.height = '0';
},
handleMouseMove(evt: MouseEvent) {
if (this.isSelecting) {
this.endX = evt.pageX;
this.endY = evt.pageY;
const selectionBox = this.$refs.selectionBox as HTMLElement;
selectionBox.style.width = `${Math.abs(this.endX - this.startX)}px`;
selectionBox.style.height = `${Math.abs(this.endY - this.startY)}px`;
selectionBox.style.left = `${Math.min(this.startX, this.endX)}px`;
selectionBox.style.top = `${Math.min(this.startY, this.endY)}px`;
}
},
handleMouseUp() {
this.isSelecting = false;
const selectionBox = this.$refs.selectionBox as HTMLElement;
selectionBox.style.display = 'none';
const selectedItems = this.items.filter((item, index) => {
const rect = this.$el.children[index].getBoundingClientRect();
return rect.left >= Math.min(this.startX, this.endX)
&& rect.top >= Math.min(this.startY, this.endY)
&& rect.right <= Math.max(this.startX, this.endX)
&& rect.bottom <= Math.max(this.startY, this.endY);
});
this.selectedItems = selectedItems;
},
},
});
</script>
```
这样,你就可以实现一个简单的拖动选择功能了。