fix: adjust useWatermark logic (#4896)

This commit is contained in:
Netfan
2024-11-15 14:06:13 +08:00
committed by GitHub
parent 788a29a8cb
commit b87d41bada
2 changed files with 42 additions and 11 deletions

View File

@@ -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<Watermark>();
const unmountedHooked = ref<boolean>(false);
const cachedOptions = ref<Partial<WatermarkOptions>>({
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),
};
}