自定义 hook
vueuse 开源库: https://vueuse.org/
hook 需要以 use 开头。
自定义 hook 案例1
<template>
<div>
<img id="img" src="../assets/images/1.JPG" alt="" width="400" height="600">
<AComponent a="123" title="tttt"></AComponent>
</div>
</template>
<script setup lang="ts">
import AComponent from "@/components/AComponent.vue";
import useBase64 from "@/hooks";
useBase64({
el: "#img",
}).then((res) => {
console.log(res.baseUrl);
});
</script>
<style scoped></style>
import { onMounted } from "vue";
type Options = {
el: string;
};
export default function (options: Options):Promise<{
baseUrl:string
}> {
const base64 = (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/JPG");
};
return new Promise((resolve) => {
onMounted(() => {
const img = document.querySelector(options.el) as HTMLImageElement;
console.log(img);
img.onload = () => {
resolve({
baseUrl:base64(img)
});
};
});
})
}