vue 的hooks-图片转Base64

vue2 hooks

主要为了提升代码的可读性

<script>
export default {
  created() {
    this.$once('hook:mounted', () => {
      xxxx.start()
    })
    this.$on('hook:mounted', () => {
      xxxx.start()
    })
    this.$on('hook:updated', () => {
      xxxx.update()
    })
    this.$once('hook:beforeDestroy', () => {
      xxxx.destroy()
    })
  }
}
</script>

vue3 hooks

为自定义hooks 提高代码的复用性, 让我们能在不同的组件中都利用 hooks 函数,类似vue2的mixins,不利于代码变量的来源查询,主文件的mixins变量容易覆盖组件内部mixins变量
Vue3 hook 库 vueuse
在这里插入图片描述

import { onMounted } from "vue"
type options = {
  el: string
}

export default function(option: options){
  return new Promise((resolve) => {
    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)
      return canvas.toDataURL('image/png')
    }
    onMounted(() => {
      const img = document.querySelector(option.el) as HTMLImageElement;
      img.onload = () => {
        resolve({Baseurl: toBase64(img)})
      }
    })
  })
}

在这里插入图片描述

<template>
  <div>
    <img id="img" src="../assets/images/dog.png" width="300" height="300">
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, toRefs, onMounted} from 'vue'
import useBase64 from '../hooks/index'
console.log("useBase64",useBase64)
useBase64({el: '#img'}).then(res => {
  console.log('res', res)
})

</script>
<style scoped lang="less">
</style>

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值