首先,需要在Vue3项目中安装vue-mouse-select插件,使用以下命令:

npm install vue-mouse-select

然后在组件中引入该插件并使用:

<template>
  <div>
    <div class="box" v-mouse-select="selectCallback">鼠标框选的区域</div>
    <div class="result">{{ result }}</div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref } from 'vue'
import { MouseSelectDirective } from 'vue-mouse-select'

export default defineComponent({
  directives: { MouseSelectDirective },
  setup() {
    const result = ref('')

    const selectCallback = (rect: DOMRect) => {
      result.value = `x:${rect.x}, y:${rect.y}, width:${rect.width}, height:${rect.height}`
    }

    return { result, selectCallback }
  },
})
</script>

以上代码中,我们使用v-mouse-select指令将需要鼠标框选的区域绑定到selectCallback回调函数上,当鼠标框选结束时,selectCallback回调函数会返回一个DOMRect对象,包含了框选区域的坐标和大小信息。我们可以将这些信息存储在组件的响应式变量中并在页面中展示出来。

需要注意的是,为了配合Typescript的类型检查,我们需要在组件中引入MouseSelectDirective指令,并将其添加到directives属性中。同时,我们在selectCallback回调函数的参数中指定了DOMRect类型,以便在编写代码时获得类型提示

Vue3 Typescript实现Windows鼠标框选div并且获取div参数

原文地址: https://www.cveoy.top/t/topic/expu 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录