自定义hook

Vue3 hook库open in new window

案例

import { onMounted } from 'vue'
 
 
type Options = {
    el: string
}

type Return = {
    Baseurl: string | null
}

export default function (option: Options): Promise<Return> {
    return new Promise((resolve) => {
        onMounted(() => {
            const img: HTMLImageElement = document.querySelector(option.el) as HTMLImageElement;
            img.onload = ():void => {
                resolve({
                    Baseurl: toBase64(file)
                })
            }
        })

        const toBase64 = (el: HTMLImageElement): string => {
            const canvas: HTMLCanvasElement = document.createElement('canvas')
            const ctx = canvas.getContext('2d') as CanvasRenderingContext2D
            canvas.width = el.width
            canvas.height = el.height
            ctx.drawImage(el, 0, 0, canvas.width,canvas.height)
            console.log(el.width);
            return canvas.toDataURL('image/png')
        }
    })
}

使用

<template>
  <div>
    
  </div>
</template>
<script setup lang="ts">
import useBase64 from './hooks'

useBase64({
  el: '#img',
}).then(()=>{
  res.baseUrl
})
</script>
Last Updated:
Contributors: haizhiguang