Custom hooks of vue3.0

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

  • Official website: official website
  • download:
    • yarn add @vueuse/core -D
  • said not to play

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
      // console.log("imgDom",imgDom); // <img id="img" src="./assets/logo.png" alt="" width="300" height="300" />
      imgDom.onload = ()=> {
    
     // 等待 img 加载完毕之后 才转化为base64
        resolve({
    
    
          Baseurl: toBase64(imgDom)
      })
      }
    })
  
    const toBase64 = (el:HTMLImageElement)=>{
    
    
      const canvas = document.createElement("canvas") // 创建标签
      const ctx = canvas.getContext("2d") // 给 canvas 指定一个文件
      canvas.width =  el.width // 给canvas 指定宽高
      canvas.height =  el.height
      ctx?.drawImage(el, 0, 0, canvas.width,canvas.height) // 制作一个画布
      return canvas.toDataURL('image/png') // 导出 base64的img
    }
  })
}

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 Layout from './layout/Layout.vue'
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
      insert image description here
    • Copy the url path to the browser url address, you can directly display the current base64 img

Guess you like

Origin blog.csdn.net/weixin_43845137/article/details/123562385