刚写了一个hooks小demo练习,这边快速简单记录一下
要求是 在页面展示 当前屏幕的宽度高度,通过点击按钮来显示
最后通过hooks函数来运行
简陋无比的展示图如下
核心思想就是 从展示页面 抽离逻辑代码 抽离出去到hooks,然后引用在本页面引用hooks函数来调用
//index.vue
<template>
<div class="box1">
<div class="box2">
<h1>hooks</h1>
<h2>页面宽度{{ screen.width }}</h2>
<h2>页面高度{{ screen.height }}</h2>
<button @click="getWH">获取页面宽度高度</button>
</div>
</div>
</template>
<script setup>
import { reactive } from "vue";
import useGetScreenWH from "@/hooks/demo/useGetScreenWH";
let { screen, getWH } = useGetScreenWH();
</script>
<style lang="less" scoped>
.box1 {
width: 300px;
height: 300px;
// border: 1px solid black;
// background-color: #fff;
position: reactive;
.box2 {
position: absolute;
width: 200px;
height: 200px;
background-color: red;
left: 50%;
top: 50%;
transform: translate(-6.25rem, -6.25rem);
}
}
</style>
这是展示页面
然后创建hooks文件夹,在里面编写hooks函数
import { reactive } from "vue";
export default function() {
const screen = reactive({ width: 0, height: 0 });
const getWH = () => {
screen.width = document.documentElement.clientWidth;
screen.height = document.documentElement.clientHeight;
};
return {
screen,
getWH,
};
}
hooks函数里面要用的api还是要引入的,比如reactive,export 导出一个function(){ }
,里面就是逻辑代码,最后一定一定要return 导出 变量 以及 函数方法。
然后回到 展示页面,引入这个hooks函数,然后解构赋值
解构出来才能在当前页面使用,好了就这样