perf: 再次提升水印 hook 性能

This commit is contained in:
pany 2023-09-01 00:43:44 +08:00
parent 413305322d
commit 9ebed9753d
2 changed files with 17 additions and 16 deletions

View File

@ -28,7 +28,7 @@ const bodyEl = ref<HTMLElement>(document.body)
/**
*
* 1. body
* 1. body
* 2.
*/
export function useWatermark(parentEl: Ref<HTMLElement | null> = bodyEl) {
@ -60,13 +60,6 @@ export function useWatermark(parentEl: Ref<HTMLElement | null> = bodyEl) {
addParentElListener(parentEl.value)
}
/** 刷新水印(防御时调用) */
const updateWatermark = debounce(() => {
clearWatermark()
createWatermarkEl()
addParentElListener(parentEl.value!)
}, 500)
/** 创建水印元素 */
const createWatermarkEl = () => {
if (watermarkEl) {
@ -128,6 +121,13 @@ export function useWatermark(parentEl: Ref<HTMLElement | null> = bodyEl) {
removeParentElListener(parentEl.value)
}
/** 刷新水印(防御时调用) */
const updateWatermark = debounce(() => {
clearWatermark()
createWatermarkEl()
addParentElListener(parentEl.value!)
}, 100)
/** 监听水印容器的变化DOM 变化 & DOM 大小变化) */
const addParentElListener = (targetNode: HTMLElement) => {
// 防止重复添加监听
@ -162,21 +162,22 @@ export function useWatermark(parentEl: Ref<HTMLElement | null> = bodyEl) {
// 当观察到变动时执行的回调
const mutationCallback = debounce((mutationList: MutationRecord[]) => {
// 水印的防御(防止用户手动删除水印元素或通过 CSS 隐藏水印)
mutationList.forEach((mutation) => {
const defense = debounce((mutation: MutationRecord) => {
switch (mutation.type) {
case "attributes":
mutation.target === watermarkEl && updateWatermark()
break
case "childList":
mutation.removedNodes.forEach((item) => {
item === watermarkEl && targetNode.appendChild(watermarkEl)
})
break
case "attributes":
if (mutation.target === watermarkEl) {
updateWatermark()
}
break
}
}, 100)
mutationList.forEach((mutation) => {
defense(mutation)
})
}, 500)
}, 100)
// 创建一个观察器实例并传入回调
observer.mutationObserver = new MutationObserver(mutationCallback)
// 以上述配置开始观察目标节点

View File

@ -11,7 +11,7 @@ const { setWatermark: setGlobalWatermark, clearWatermark: clearGlobalWatermark }
<div class="app-container">
<h4>
该示例是演示通过调用 hook开启或关闭水印
支持局部全局自定义样式颜色透明度字体大小字体倾斜角度等 并自带一定的防删除和自适应功能
支持局部全局自定义样式颜色透明度字体大小字体倾斜角度等并自带防御防删防隐藏和自适应功能
</h4>
<div ref="localRef" class="local" />
<el-button-group>