自定义Hooks实现Loading状态控制
在Vue项目中,经常需要对Loading状态进行管理以提升用户体验。本文将介绍如何使用Vue自定义Hooks实现Loading状态的控制,并提供了一个名为`useLoading`的自定义Hook,能够方便地管理Loading状态。
在Vue开发中,我们经常需要实现一些特定功能,比如在网站上显示水印以防止内容被篡改。本文将介绍如何使用Vue和一些特定的Hooks来实现水印防篡改功能。
在Vue中,Hooks是一种用于在组件中复用逻辑的方式。它们可以让你在组件之间共享逻辑,从而使代码更加清晰和易于维护。在本文中,我们将使用一个名为useWatermark
的自定义Hooks来实现水印防篡改功能。
首先,我们需要定义一个名为useWatermark
的Hooks。这个Hooks接受两个参数:文本内容和字体大小。然后,它将创建一个带有水印的画布,并将其插入到网页中。这样,无论用户如何修改网页内容,水印都会始终保留在页面上。
import { computed } from 'vue'
interface Props {
text: string
fontSize: number
}
export const useWatermark = (props: Props) => {
return computed(() => {
const canvas = document.createElement('canvas')
const devicePixelRatio = window.devicePixelRatio || 1
const fontSize = props.fontSize * devicePixelRatio
const font = fontSize + 'px ' + 'Microsoft YaHei'
const ctx = canvas.getContext('2d')
ctx!.font = font
const { width } = ctx?.measureText(props.text) || { width: 0 }
const canvasSize = Math.max(100, width)
canvas.width = canvasSize
canvas.height = canvasSize
ctx?.translate(canvas.width / 2, canvas.height / 2)
ctx?.rotate((Math.PI / 180) * -36)
ctx!.fillStyle = 'rgba(0,0,0,0.3)'
ctx!.textAlign = 'center'
ctx!.textBaseline = 'middle'
ctx!.fillText(props.text, 0, 0)
return {
base64: canvas.toDataURL(),
size: canvasSize / devicePixelRatio
}
})
}
在上面的代码中,我们首先创建了一个画布,然后根据用户传入的字体大小和文本内容来绘制水印。最后,我们将水印转换为Base64格式,并返回给调用者。
接下来,我们将在Vue组件中使用上述的useWatermark
Hooks来实现水印防篡改功能。
<template>
<div class="watermark" ref="watermarkRef">
<slot />
</div>
</template>
<script setup lang="ts">
import { onBeforeUnmount, onMounted, ref } from 'vue'
import { useWatermark } from '@/hooks/watremark'
interface Props {
text?: string
fontSize?: number
}
const props = withDefaults(defineProps<Props>(), {
text: 'Superficial',
fontSize: 16
})
const bg = useWatermark(props)
let div: HTMLDivElement | null
const watermarkRef = ref<HTMLDivElement|null>(null)
const resetWatermark = () => {
if (!watermarkRef.value) {
return
}
if (div) {
div.remove()
}
const { base64, size } = bg.value
div = document.createElement('div')
div.style.position = 'absolute'
div.style.backgroundImage = `url(${base64})`
div.style.backgroundSize = `${size}px ${size}px`
div.style.backgroundRepeat = 'repeat'
div.style.zIndex = '9999'
div.style.inset = '0'
div.style.pointerEvents = 'none'
document.body.style.backgroundImage = 'none'
watermarkRef.value.appendChild(div)
}
const ob = new MutationObserver((mutations: MutationRecord[]) => {
for (const entry of mutations) {
for (const node of entry.removedNodes) {
if(node === div) {
resetWatermark()
}
}
// 处理修改
if (entry.target === div) {
resetWatermark()
}
}
})
onMounted(() => {
resetWatermark()
ob.observe(watermarkRef.value!, {
childList: true,
subtree: true,
attributes: true
})
})
onBeforeUnmount(() => {
ob.disconnect()
})
</script>
<style lang="scss" scoped>
.watermark {
position: relative;
flex: 1;
min-height: 100vh;
}
</style>
在上面的Vue组件中,我们首先引入了useWatermark
Hooks,并传入了水印的文本内容和字体大小。然后,我们在组件的生命周期钩子函数中使用了该Hooks来创建水印,并将其插入到页面中。