视频加载失败

Vue Hook 实现打点

209 字
1 分钟
Vue Hook 实现打点

【一】JS代码#

  • \src\hook\UsePoint.js
import {onBeforeUnmount, onMounted, reactive} from "vue";
export default function () {
let point = reactive({
x: 0,
y: 0
})
function getPoint(event) {
console.log(event.pageX)
console.log(event.pageY)
point.x = event.pageX
point.y = event.pageY
}
// 挂在完成开始执行
onMounted(() => {
window.addEventListener('click', getPoint)
})
// 接除挂载时执行
onBeforeUnmount(() => {
console.log('sss')
window.removeEventListener('click', getPoint)
})
return point
}

【二】PointView#

  • src\components\PointView.vue
<script setup>
</script>
<template>
<div>
<hr>
<h2>x坐标:>>>>{{ point.x }}</h2>
<hr>
<h2>y坐标:>>>>{{ point.y }}</h2>
<hr>
</div>
</template>
<script>
import {onBeforeUnmount, onMounted, reactive, toRefs} from "vue";
import UsePoint from "@/hook/UsePoint";
export default {
name: 'PointView',
setup() {
let point = UsePoint()
console.log(point)
return {point}
}
}
</script>
<style scoped>
</style>

【三】HomeView#

  • src\views\HomeView.vue
<script setup>
</script>
<template>
<div>
<h1>这是一个坐标信息</h1>
<button @click="showFunc">点我启用/关闭</button>
<br>
<PointView v-if="show"></PointView>
</div>
</template>
<script>
// 导入ref函数
import {ref, reactive, toRefs, onMounted, onBeforeUnmount} from "vue";
// 导入reactive函数
import PointView from "@/components/PointView.vue";
export default {
name: "HomeView",
components: {
PointView,
},
setup() {
let show = ref(true);
const showFunc = () => {
show.value = !show.value;
}
return {show, showFunc}
}
}
</script>

支持与分享

如果这篇文章对你有帮助,欢迎分享给更多人或打赏支持!

打赏
Vue Hook 实现打点
https://firefly.cuteleaf.cn/posts/framework/vue/150vue之hook实现打点/
作者
Dream
发布于
2023-08-21
许可协议
CC BY-NC-SA 4.0

评论区

Profile Image of the Author
Dream
Hello, I'm Dream.
公告
欢迎来到我的博客!爱学习爱进步。
分类
标签
最新动态
站点统计
文章
367
分类
6
标签
201
总字数
804,820
运行时长
0 天
最后活动
0 天前
站点信息
构建平台
Vercel
博客版本
Firefly v6.16.8
文章许可
CC BY-NC-SA 4.0
文章目录