自学内容网 自学内容网

vue3 监听鼠标移入移出

1. 通过`v-on`指令监听

监听`mouseenter`和`mouseleave`事件

<template>

  <div @mouseenter="handleMouseEnter" @mouseleave="handleMouseLeave">

    鼠标移入移出我来试试

  </div>

</template>

<script setup>

const handleMouseEnter = () => {

  console.log("鼠标移入");

};

const handleMouseLeave = () => {

  console.log("鼠标移出");

};

</script>

2. 使用`ref`和`addEventListener`

先使用`ref`获取 DOM 元素的引用,然后在`onMounted`钩子函数中通过`addEventListener`来监听鼠标移入移出事件,在`onUnmounted`钩子函数中移除事件监听,以避免内存泄漏。

<template>

  <div ref="targetDiv">鼠标移入移出我来试试</div>

</template>

<script setup>

import { onMounted, onUnmounted, ref } from "vue";

const targetDiv = ref(null);

const handleMouseEnter = () => {

  console.log("鼠标移入");

};

const handleMouseLeave = () => {

  console.log("鼠标移出");

};

onMounted(() => {

  if (targetDiv.value) {

    targetDiv.value.addEventListener("mouseenter", handleMouseEnter);

    targetDiv.value.addEventListener("mouseleave", handleMouseLeave);

  }

});

onUnmounted(() => {

  if (targetDiv.value) {

    targetDiv.value.removeEventListener("mouseenter", handleMouseEnter);

    targetDiv.value.removeEventListener("mouseleave", handleMouseLeave);

  }

});

</script>

3. 通过组合式 API 监听

使用`@vueuse/core`库中的`useMouseEnter`和`useMouseLeave`组合式函数来监听鼠标移入移出事件。

<template>

  <div ref="targetDiv">鼠标移入移出我来试试</div>

</template>

<script setup>

import { ref } from "vue";

import { useMouseEnter, useMouseLeave } from "@vueuse/core";

const targetDiv = ref(null);

const onMouseEnter = () => {

  console.log("鼠标移入");

};

const onMouseLeave = () => {

  console.log("鼠标移出");

};

useMouseEnter(targetDiv, onMouseEnter);

useMouseLeave(targetDiv, onMouseLeave);

</script>


原文地址:https://blog.csdn.net/weixin_64684095/article/details/145130408

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!