Custom hooks of vue3.0
what are hooks
Essentially, a hook is a function, but a hook encapsulates the component apis (ref, reactive, calculated, watch, life cycle functions) in the setup combination function, etc., and extracts the code (public code, public components, etc.) , which makes the code more concise
hook is similar to mixin in vue2
vueuse encapsulates many public hook functions
Convert img of custom hook to base64
hook / tobase64.ts
import {
onMounted } from "vue"
type Options = {
el: String
}
export default function ( options: Options) : Promise< {
baseUrl: string} > {
return new Promise ( ( resolve) => {
onMounted ( ( ) => {
let imgDom: HTMLImageElement = document. querySelector ( options. el) as HTMLImageElement
imgDom. onload = ( ) => {
resolve ( {
Baseurl: toBase64 ( imgDom)
} )
}
} )
const toBase64 = ( el: HTMLImageElement) => {
const canvas = document. createElement ( "canvas" )
const ctx = canvas. getContext ( "2d" )
canvas. width = el. width
canvas. height = el. height
ctx? . drawImage ( el, 0 , 0 , canvas. width, canvas. height)
return canvas. toDataURL ( 'image/png' )
}
} )
}
use
< template>
< ! -- < Layout> < / Layout> -- >
< div>
< img id= "img" src= "./assets/logo.png" alt= "" width= "300" height= "300" / >
转化为base64
< / div>
< / template>
< script setup lang= "ts" >
import useBase64 from './hook/tobase64'
useBase64 ( {
el: '#img' ,
} ) . then ( ( res) => {
console. log ( 'res' , res. Baseurl)
} )
< / script>
< style lang= "scss" >
html,
body,
#app {
height: 100 % ;
width: 100 % ;
overflow: hidden;
}
< / style>
Effect
url path converted to base64
Copy the url path to the browser url address, you can directly display the current base64 img