Vue3 自定义Hook
    主要用来处理复用代码逻辑的一些封装
    这个在vue2 就已经有一个东西是Mixins
    mixins就是将这些多个相同的逻辑抽离出来,各个组件只需要引入mixins,就能实现一次写代码,多组件受益的效果。
    弊端就是 会涉及到覆盖的问题
    组件的data、methods、filters会覆盖mixins里的同名data、methods、filters。
    image.png
    第二点就是 变量来源不明确(隐式传入),不利于阅读,使代码变得难以维护。
    Vue3 的自定义的hook

    • Vue3 的 hook函数 相当于 vue2 的 mixin, 不同在与 hooks 是函数
    • Vue3 的 hook函数 可以帮助我们提高代码的复用性, 让我们能在不同的组件中都利用 hooks 函数

    Vue3 hook 库Get Started | VueUse
    案例

    1. import { onMounted } from 'vue'
    2. type Options = {
    3. el: string
    4. }
    5. type Return = {
    6. Baseurl: string | null
    7. }
    8. export default function (option: Options): Promise<Return> {
    9. return new Promise((resolve) => {
    10. onMounted(() => {
    11. const file: HTMLImageElement = document.querySelector(option.el)
    12. as HTMLImageElement;
    13. file.onload = ():void => {
    14. resolve({
    15. Baseurl: toBase64(file)
    16. })
    17. }
    18. })
    19. const toBase64 = (el: HTMLImageElement): string => {
    20. const canvas: HTMLCanvasElement = document.createElement('canvas')
    21. const ctx = canvas.getContext('2d') as CanvasRenderingContext2D
    22. canvas.width = el.width
    23. canvas.height = el.height
    24. ctx.drawImage(el, 0, 0, canvas.width,canvas.height)
    25. console.log(el.width);
    26. return canvas.toDataURL('image/png')
    27. }
    28. })
    29. }



    ————————————————
    版权声明:本文为CSDN博主「小满zs」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
    原文链接:https://blog.csdn.net/qq1195566313/article/details/123271189