vue3 之 封装hooks

发布时间 2023-12-06 11:28:48作者: persist_in

  注意:

    使用 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

npm install pinia 或者 yarn add pinia

      在本地状态管理中定义控制侧栏菜单的变量(layoutStore)

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
    }
})

      侧栏伸缩的逻辑

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)
    })
}

    ② 网页自动伸缩

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

import { useResize } from '@/hooks/useResize.js';

const $useResize = useResize();
let { width, height } = $useResize

  再将返回的数据进行使用

 

   注:该文档为个人理解所写,有误可建议修改(也可留下您宝贵的建议哦~)