-
什么是hook?——本质是一个函数,把setup函数中使用的Composition API(ref、reactive、计算属性、监听属性、方法、生命周期钩子、计算属性、)进行了封装。
-
类似于vue2.x中的mixin混入。
-
自定义hook的优势: 复用代码, 让setup中的逻辑更清楚易懂、将组合体现的淋淋尽致。
eg: 自定义hooks函数实现鼠标“打点”
src/hooks/usePoint.js
import { reactive, onMounted, onBeforeUnmount } from 'vue'
export default function () {
// 实现鼠标“打点”相关的数据
let point = reactive({
x: 0,
y: 0,
});
// 实现鼠标“打点”相关的方法
function savePoint(event) {
point.x = event.pageX;
point.y = event.pageY;
console.log(event.pageX, event.pageY);
}
// 实现鼠标“打点”相关的生命周期钩子
onMounted(() => { // 定义点击事件, 获取坐标
window.addEventListener("click", savePoint);
});
onBeforeUnmount(() => { // 组件销毁前将事件销毁
window.removeEventListener('click', savePoint)
})
// 将数据交出
return point
}
// export default savePoint
src/components/Demo.vue
<template>
<h1>一个人的信息</h1>
<h2>当前求和为: {{ sum }}</h2>
<button @click="sum++">点我+1</button>
<hr />
<h2>当前点击鼠标的坐标为- x:{{ point.x }} y: {{ point.y }}</h2>
</template>
<script>
// 组合式API: 就是引入形形色色的东西,然后组合到 setup函数中去!
import { ref} from "vue";
// 引入自定义hooks函数
import usePoint from '../hooks/usePoint'
export default {
name: "Demo",
setup() {
let sum = ref(0);
// 接收返回的数据
let point = usePoint()
// 将数据抛出
return { sum, point };
},
};
</script>
App.vue
<template>
<button @click="isShowDemo = !isShowDemo"> Demo</button>
<Demo v-if="isShowDemo"></Demo>
</template>
<script>
import Demo from "./components/Demo.vue";
import { ref } from 'vue'
export default {
name: "App",
components: { Demo },
setup() {
let isShowDemo = ref(true)
return { isShowDemo }
}
};
</script>