perf: 优化部分 composable 代码细节

This commit is contained in:
pany 2024-11-25 11:09:23 +08:00
parent b5210eb452
commit 0b517855b6
3 changed files with 8 additions and 12 deletions

View File

@ -2,6 +2,7 @@ import { getActiveThemeName, setActiveThemeName } from "@/utils/cache/local-stor
import { ref, watchEffect } from "vue" import { ref, watchEffect } from "vue"
const DEFAULT_THEME_NAME = "normal" const DEFAULT_THEME_NAME = "normal"
type DefaultThemeName = typeof DEFAULT_THEME_NAME type DefaultThemeName = typeof DEFAULT_THEME_NAME
/** 注册的主题名称, 其中 DefaultThemeName 是必填的 */ /** 注册的主题名称, 其中 DefaultThemeName 是必填的 */

View File

@ -11,7 +11,7 @@ function setTitle(title?: string) {
dynamicTitle.value = title ? `${VITE_APP_TITLE} | ${title}` : VITE_APP_TITLE dynamicTitle.value = title ? `${VITE_APP_TITLE} | ${title}` : VITE_APP_TITLE
} }
/** 监听标题变化 */ // 监听标题变化
watch(dynamicTitle, (value, oldValue) => { watch(dynamicTitle, (value, oldValue) => {
if (document && value !== oldValue) { if (document && value !== oldValue) {
document.title = value document.title = value

View File

@ -8,10 +8,10 @@ interface Observer {
parentElResizeObserver?: ResizeObserver parentElResizeObserver?: ResizeObserver
} }
type DefaultConfig = typeof defaultConfig type DefaultConfig = typeof DEFAULT_CONFIG
/** 默认配置 */ /** 默认配置 */
const defaultConfig = { const DEFAULT_CONFIG = {
/** 防御(默认开启,能防御水印被删除或隐藏,但可能会有性能损耗) */ /** 防御(默认开启,能防御水印被删除或隐藏,但可能会有性能损耗) */
defense: true, defense: true,
/** 文本颜色 */ /** 文本颜色 */
@ -54,14 +54,11 @@ export function useWatermark(parentEl: Ref<HTMLElement | null> = bodyEl) {
/** 设置水印 */ /** 设置水印 */
const setWatermark = (text: string, config: Partial<DefaultConfig> = {}) => { const setWatermark = (text: string, config: Partial<DefaultConfig> = {}) => {
if (!parentEl.value) { if (!parentEl.value) return console.warn("请在 DOM 挂载完成后再调用 setWatermark 方法设置水印")
console.warn("请在 DOM 挂载完成后再调用 setWatermark 方法设置水印")
return
}
// 备份文本 // 备份文本
backupText = text backupText = text
// 合并配置 // 合并配置
mergeConfig = { ...defaultConfig, ...config } mergeConfig = { ...DEFAULT_CONFIG, ...config }
// 创建或更新水印元素 // 创建或更新水印元素
watermarkEl ? updateWatermarkEl() : createWatermarkEl() watermarkEl ? updateWatermarkEl() : createWatermarkEl()
// 监听水印元素和容器元素的变化 // 监听水印元素和容器元素的变化
@ -228,10 +225,8 @@ export function useWatermark(parentEl: Ref<HTMLElement | null> = bodyEl) {
observer.parentElResizeObserver.observe(targetNode) observer.parentElResizeObserver.observe(targetNode)
} }
/** 在组件卸载前移除水印以及各种监听 */ // 在组件卸载前移除水印以及各种监听
onBeforeUnmount(() => { onBeforeUnmount(() => clearWatermark())
clearWatermark()
})
return { setWatermark, clearWatermark } return { setWatermark, clearWatermark }
} }