自定义Hooks
主要用来处理经常复用的代码逻辑的一些封装 这个在vue2就已经有一个东西是Mxins mixins就是将这些多个相同的逻辑抽离出来,各个组件只需要引入micins,就能实现一次写代码,多组件受益的效果。 弊端就是会涉及到覆盖的问题
Vue3自定义Hooks
Vue自带的hooks
import { useAttrs,useSlots } from 'vue'
let attr = useAttrs() //获取所有传过来的参数
let slots= useSlots() //获取插槽
ts文件
typescript
import { onMounted } from "vue";
type Options = {
el: string;
};
export default function (options: Options): Promise<{ baseUrl: string }> {
return new Promise((resolve) => {
onMounted(() => {
let img: HTMLImageElement = document.querySelector(
options.el
) as HTMLImageElement;
img.onload = () => {
resolve({
baseUrl: base64(img),
});
};
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);
console.log(el.src);
return canvas.toDataURL("image/png");
};
});
});
}页面使用
vue
import useBase64 from '../../hooks/index'
useBase64({ el: '#img' }).then(res => {
console.log(res.baseUrl);
})