上一篇:
vue3生命周期https://blog.csdn.net/qq_42543244/article/details/122398873?spm=1001.2014.3001.5501今天主要需要记录vue3的自定义hook函数,vue3自定义hook函数与vue2的mixin是有点相似的,
进行代码的复用。为了更好的演示,我写了两个测试的子组件。
父组件:
<template>
<button @click="isShow = !isShow">切换组件</button>
<demo v-if="isShow"></demo>
<test v-else></test>
</template>
<script>
import { ref } from "vue";
import Demo from "@/components/Demo.vue";
import Test from "@/components/Test.vue";
export default {
name: "App",
components: {
Demo,
Test,
},
setup() {
let isShow = ref(true);
return {
isShow,
};
},
};
</script>
子组件 Demo.vue
<template>
<div>Demo组件内容</div>
<h2>当前鼠标点击的位置坐标x:{{ point.x }} , y:{{ point.y }}</h2>
</template>
<script>
/*
hooks的本质就是一个函数,把setup函数中使用的composition api进行了封装
类似于vue2中的mixin
自定义hook的优势:复用代码,让setup中的逻辑可以更加的清晰
*/
import userPoint from "@/hooks/userPoint";
export default {
name: "Demo",
setup() {
let point = userPoint();
return { point };
},
};
</script>
子组件 Test.vue
<template>
<div>Test组件内容</div>
<h2>test:当前鼠标点击的位置坐标x:{{ point.x }} , y:{{ point.y }}</h2>
</template>
<script>
import userPoint from "@/hooks/userPoint";
export default {
name: "Test",
setup() {
let point = userPoint();
return { point };
},
};
</script>
userPoint.js (也就是我们自定义的hook函数)
import {
reactive,
onMounted,
onUnmounted
} from "vue";
export default function () {
let point = reactive({
x: 0,
y: 0,
});
function getPageXY(event) {
point.x = event.pageX;
point.y = event.pageY;
}
onMounted(() => {
window.addEventListener("click", getPageXY);
});
onUnmounted(() => {
window.removeEventListener("click", getPageXY);
});
return point
}
下一篇:
vue3 toRef&toRefshttps://blog.csdn.net/qq_42543244/article/details/122715199