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>