From b87d41bada9072b172e3a9373c40dbb8125ca8e5 Mon Sep 17 00:00:00 2001 From: Netfan Date: Fri, 15 Nov 2024 14:06:13 +0800 Subject: [PATCH] fix: adjust `useWatermark` logic (#4896) --- packages/effects/hooks/src/use-watermark.ts | 25 ++++++++++++----- .../views/demos/features/watermark/index.vue | 28 ++++++++++++++++--- 2 files changed, 42 insertions(+), 11 deletions(-) diff --git a/packages/effects/hooks/src/use-watermark.ts b/packages/effects/hooks/src/use-watermark.ts index 765cdfb5..c3f56eaf 100644 --- a/packages/effects/hooks/src/use-watermark.ts +++ b/packages/effects/hooks/src/use-watermark.ts @@ -1,8 +1,11 @@ import type { Watermark, WatermarkOptions } from 'watermark-js-plus'; -import { nextTick, onUnmounted, ref } from 'vue'; +import { nextTick, onUnmounted, readonly, ref } from 'vue'; + +import { updatePreferences } from '@vben/preferences'; const watermark = ref(); +const unmountedHooked = ref(false); const cachedOptions = ref>({ advancedStyle: { colorStops: [ @@ -45,7 +48,7 @@ export function useWatermark() { ...options, }; watermark.value = new Watermark(cachedOptions.value); - + updatePreferences({ app: { watermark: true } }); await watermark.value?.create(); } @@ -62,16 +65,24 @@ export function useWatermark() { } function destroyWatermark() { - watermark.value?.destroy(); + if (watermark.value) { + watermark.value.destroy(); + watermark.value = undefined; + } + updatePreferences({ app: { watermark: false } }); } - onUnmounted(() => { - destroyWatermark(); - }); + // 只在第一次调用时注册卸载钩子,防止重复注册以致于在路由切换时销毁了水印 + if (!unmountedHooked.value) { + unmountedHooked.value = true; + onUnmounted(() => { + destroyWatermark(); + }); + } return { destroyWatermark, updateWatermark, - watermark, + watermark: readonly(watermark), }; } diff --git a/playground/src/views/demos/features/watermark/index.vue b/playground/src/views/demos/features/watermark/index.vue index 9f819e51..77b3f179 100644 --- a/playground/src/views/demos/features/watermark/index.vue +++ b/playground/src/views/demos/features/watermark/index.vue @@ -4,7 +4,12 @@ import { useWatermark } from '@vben/hooks'; import { Button, Card } from 'ant-design-vue'; -const { destroyWatermark, updateWatermark } = useWatermark(); +const { destroyWatermark, updateWatermark, watermark } = useWatermark(); + +async function recreateWaterMark() { + destroyWatermark(); + await updateWatermark({}); +} async function createWaterMark() { await updateWatermark({ @@ -21,7 +26,7 @@ async function createWaterMark() { ], type: 'linear', }, - content: 'hello my watermark', + content: `hello my watermark\n${new Date().toLocaleString()}`, globalAlpha: 0.5, gridLayoutOptions: { cols: 2, @@ -57,10 +62,25 @@ async function createWaterMark() { - - + +