假期第三篇,对于基础的知识点,我感觉自己还是很薄弱的。
趁着假期,再去复习一遍
【vue3 】hook函数
hook本质上是一个函数,把setup中使用的Composition API进行了封装
假设需求是获取当前点击时鼠标的坐标
<template>
<div>
<h2>当前求和的值为:{{ sum }}</h2>
<button @click="sum++">点我+1</button>
<hr />
<h2>当前点击时鼠标的坐标为:x:{{ point.x }},y:{{ point.y }}</h2>
</div>
</template>
<script >
import { ref, reactive, onMounted, onBeforeMount } from "vue";
export default {
name: "demo",
setup() {
let sum = ref(0);
let point = reactive({
x: 0,
y: 0,
});
onMounted(() => {
window.addEventListener("click", savePoint);
});
onBeforeMount(() => {
window.removeEventListener("click", savePoint);
});
function savePoint(event) {
(point.x = event.pageX), (point.y = event.pageY);
}
return {
sum,
point,
};
},
};
</script>
假设还有其他页面也需要用到点击鼠标求坐标的需求,那就可以把这些代码都放到hook函数中,实现代码的复用
src下新建hoos文件夹,新建usePoint.js,有两种写法
写法1:
import { reactive, onMounted, onBeforeMount } from "vue";
function savePoint() {
let point = reactive({
x: 0,
y: 0,
});
onMounted(() => {
window.addEventListener("click", savePoint);
});
onBeforeMount(() => {
window.removeEventListener("click", savePoint);
});
function savePoint(event) {
(point.x = event.pageX), (point.y = event.pageY);
}
return {
point
}
}
export default savePoint
在页面中使用
<template>
<div>
<h2>当前求和的值为:{{ sum }}</h2>
<button @click="sum++">点我+1</button>
<hr />
<h2>当前点击时鼠标的坐标为:x:{{ point.x }},y:{{ point.y }}</h2>
</div>
</template>
<script >
import { ref} from "vue";
import savePoint from "./hooks/usePoint";
export default {
name: "demo",
setup() {
let sum = ref(0);
const { point } = savePoint();
watch(point, (newVal, oldVal) => {
console.log("point变了", newVal, oldVal);
});
return {
sum,
point,
};
},
};
</script>
写法2:
import { reactive, onMounted, onBeforeMount } from "vue";
export default function () {
let point = reactive({
x: 0,
y: 0,
});
onMounted(() => {
window.addEventListener("click", savePoint);
});
onBeforeMount(() => {
window.removeEventListener("click", savePoint);
});
function savePoint(event) {
(point.x = event.pageX), (point.y = event.pageY);
}
return point
}
在页面中使用文章来源:https://www.toymoban.com/news/detail-729693.html
<template>
<div>
<h2>当前求和的值为:{{ sum }}</h2>
<button @click="sum++">点我+1</button>
<hr />
<h2>当前点击时鼠标的坐标为:x:{{ point.x }},y:{{ point.y }}</h2>
</div>
</template>
<script >
import { ref } from "vue";
import usePoint from "./hooks/usePoint";
export default {
name: "demo",
setup() {
let sum = ref(0);
let point = usePoint();
watch(point, (newVal, oldVal) => {
console.log("point变了", newVal, oldVal);
});
return {
sum,
point,
};
},
};
</script>
文章来源地址https://www.toymoban.com/news/detail-729693.html
到了这里,关于【vue3】自定义hook函数的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!