首先编写一个鼠标移动位置的功能
<template>
<div>
<p>x坐标:{{x}}</p>
<p>y坐标:{{y}}</p>
<div class="box" @mousemove="onMpuseMove"></div>
</div>
</template>
<script>
import {ref} from 'vue';
export default {
setup () {
const x = ref(-1);
const y = ref(-1);
const onMpuseMove = (event) => {
x.value = event.pageX;
y.value = event.pageY;
}
return {
x,
y,
onMpuseMove
}
}
}
</script>
<style scoped>
.box{
width: 500px;
height: 500px;
background-color: red;
}
</style>
假如其他地方也需要这个功能,我们就需要复用。所以这里就用到了hook技术。
创建文件 useMousePosition.js
import { ref } from 'vue';
export default function () {
const x = ref(-1);
const y = ref(-1);
const onMpuseMove = (event) => {
x.value = event.pageX;
y.value = event.pageY;
}
return {
x,
y,
onMpuseMove
}
}
在需要使用的地方引入
<template>
<div>
<p>x坐标:{{x}}</p>
<p>y坐标:{{y}}</p>
<div class="box" @mousemove="onMpuseMove"></div>
</div>
</template>
<script>
import useMousePosition from './useMousePosition';
export default {
setup () {
const {x,y,onMpuseMove} = useMousePosition();
return {
x,
y,
onMpuseMove
}
}
}
</script>
<style scoped>
.box{
width: 500px;
height: 500px;
background-color: red;
}
</style>
本文暂时没有评论,来添加一个吧(●'◡'●)