fix: adjust `useWatermark` logic (#4896)

pull/48/MERGE
Netfan 2024-11-15 14:06:13 +08:00 committed by GitHub
parent 788a29a8cb
commit b87d41bada
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
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),
};
}

View File

@ -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() {
</template>
<Card title="使用">
<Button class="mr-2" type="primary" @click="createWaterMark()">
<Button
:disabled="!!watermark"
class="mr-2"
type="primary"
@click="recreateWaterMark"
>
创建水印
</Button>
<Button danger @click="destroyWatermark"></Button>
<Button
:disabled="!watermark"
class="mr-2"
type="primary"
@click="createWaterMark"
>
更新水印
</Button>
<Button :disabled="!watermark" danger @click="destroyWatermark">
移除水印
</Button>
</Card>
</Page>
</template>