hook 可以理解为类似于vue2中mixin 用法------------公共方法封装
hook优点:复用代码,让setup中的逻辑更通俗,更简洁
src下新建hook文件,hook 文件下新建 .js文件
举个例子: 需求:拿到鼠标的 x y 值
- import { onBeforeUnmount, onMounted, reactive } from "vue";
- export default function usePoint() {
- let point = reactive({
- x: 0,
- y: 0,
- });
- function savePoint(e) {
- point.x = e.pageX;
- point.y = e.pageY;
- }
- onMounted(() => {
- window.addEventListener("click", savePoint);
- });
- onBeforeUnmount(() => {
- //事件销毁
- window.removeEventListener("click", savePoint);
- });
- return point // 把数据return出去
- }
页面引入公共方法:usePoint
- <div>
- <h2>当前鼠标所在位置坐标x为{{ point1.x }} y轴坐标为{{ point1.y }}h2>
- div>
-
- <script>
- import usePoint from "../src/hooks/usePoint";
- export default {
- setup() {
- let point1 = usePoint();
- return { usePoint, point1 };
- },
- };
- script>
-
- <style>
- style>