vue3 之 封装hooks
注意:
使用 Hooks 来做的话,需要封装一个以 use 开头的函数,自定义 Hooks 有一个潜规则,就是要 use 开头
一、相关链接
① 已经封装好可直接使用的:https://vueuse.org/core/useMounted/
② 为什么要在Vue3中多使用Hooks?好处是啥? : https://zhuanlan.zhihu.com/p/649005492?utm_id=0
③ Vue3中使用hooks,hooks究竟是个啥?如何理解 : https://blog.csdn.net/qq_21561833/article/details/126798853
④ vue3的hooks 和 react的hooks有什么区别 : https://www.5axxw.com/questions/simple/3m61ql
⑤ vue3:一个小例子了解hook是什么 : https://www.jianshu.com/p/7e38a4da6637
⑥ 为什么要在Vue3中多使用Hooks?好处是啥? : https://juejin.cn/post/7264747090814910524
二、hooks的作用
① 方便管理组件状态,并且实现数据的响应式更新
② 可以在多个组件中共享和复用
③ 无论是 vue 还是 react, 通过 Hooks 写法都能做到,将“分散在各种声明周期里的代码块”,通过 Hooks 的方式将相关的内容聚合到一起。
三、平时封装的hooks
① 侧栏伸缩
vue3中使用的状态管理是pinia:https://pinia.vuejs.org/
安装pinia
1 | npm install pinia 或者 yarn add pinia |
在本地状态管理中定义控制侧栏菜单的变量(layoutStore)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | import { defineStore } from 'pinia' import { ref } from 'vue' export const layoutStore = defineStore( 'layoutStore' , () => { // 定义变量控制菜单的展开 let collapse = ref<boolean>( false ) // 定义一个函数控制collapse的值 let handleCollapse = () => { collapse.value = !collapse.value } let changeCollapse = (flag: boolean) => { collapse.value = flag } return { collapse, handleCollapse, changeCollapse } }) |
侧栏伸缩的逻辑
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | import { onMounted } from 'vue' import { layoutStore } from '@/store/layoutStore' export const userCollapse = () => { let $layoutStore = layoutStore() let width = 600; let clientW = document.body.clientWidth; if (clientW > width) { $layoutStore.changeCollapse( false ) } else { $layoutStore.changeCollapse( true ) } onMounted(() => { userCollapse(); window.addEventListener( 'resize' , userCollapse) }) } |
② 网页自动伸缩
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | import { ref, onMounted, onUnmounted } from 'vue' export const useResize = () => { const minWidth = 900 const minHeight = 768 const width = ref(window.innerWidth >= minWidth ? window.innerWidth : minWidth) const height = ref(window.innerHeight >= minHeight ? window.innerHeight : minHeight) const handleResize = () => { if (window.innerWidth >= minWidth && window.innerHeight >= minHeight) { width.value = window.innerWidth height.value = window.innerHeight } } onMounted(() => { window.addEventListener( 'resize' , handleResize) }) onUnmounted(() => { window.removeEventListener( 'resize' , handleResize) }) return { width, height } } |
如果还有其他需求的可见:https://vueuse.org/core/useMounted/
四、如何使用hooks
在你需要的页面进行引入:比如引入useResize这一个hooks
1 2 3 4 | import { useResize } from '@/hooks/useResize.js' ; const $useResize = useResize(); let { width, height } = $useResize |
再将返回的数据进行使用
注:该文档为个人理解所写,有误可建议修改(也可留下您宝贵的建议哦~)
本文作者:persist_in
本文链接:https://www.cnblogs.com/persistIn/p/17879136.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步