vue3.0之自定义 hooks
- 什么是 hooks
- 本质而言,hook就是一个函数,只不过hook是把 setup组合函数之中的 组件api(ref、reactive、conputed、watch、生命周期函数)等进行了封装抽离代码(公共代码,公共组件等),这样使得代码更加简洁
- hook 类似于 vue2之中的 mixin
vueuse 封装了很多公共的 hook函数
1:自定义hook 之 img转化为 base64
1-1hook / 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')
}
})
}
1-2使用
<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>
- 效果
- 转化为base64的url路径
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/68f545e697e7ac771db9699ac7d45658.png)
- 把url路径 copy 到浏览器url地址之中,可以直接显示当前base64 的img
2:自定义hook 之 倒计时
2-1 hook / useInterval.ts
import { onMounted, ref } from 'vue'
export function useInterval(end: number) {
const count = ref<number>(end)
const timer = ref<NodeJS.Timeout>()
onMounted(() => {
timer.value = setInterval(() => {
count.value--
if (count.value === 0) {
clearInterval(timer.value)
}
}, 1000)
})
return [count]
}
2-2 使用 倒计时 hook
<div>count2 - {{ count2 }}</div>
import { useInterval } from '@/hook/useInterval.ts'
const [count2] = useInterval(5)