From 6f3829c36bc4b5d5b657a8fafd1c9fc7eaaeee97 Mon Sep 17 00:00:00 2001 From: KUN1007 Date: Thu, 24 Aug 2023 23:59:37 +0800 Subject: [PATCH] pref: debounce --- src/components/WangEditor.vue | 9 +++++++-- src/utils/debounce.ts | 3 +++ src/views/edit/Edit.vue | 13 ++++++++++--- 3 files changed, 20 insertions(+), 5 deletions(-) diff --git a/src/components/WangEditor.vue b/src/components/WangEditor.vue index a2227417..71f7a0d6 100644 --- a/src/components/WangEditor.vue +++ b/src/components/WangEditor.vue @@ -12,6 +12,8 @@ import { useKUNGalgameEditStore } from '@/store/modules/edit' import { storeToRefs } from 'pinia' // 导入过滤 xss 的工具 import DOMPurify from 'dompurify' +// 导入防抖函数 +import { debounce } from '@/utils/debounce' const topicData = storeToRefs(useKUNGalgameEditStore()) @@ -70,11 +72,14 @@ onBeforeUnmount(() => { // 编辑器文本改变时自动保存数据 const handleChange = (editor: IDomEditor) => { editorRef.value = editor - // 防抖 - setTimeout(() => { + // 创建一个防抖处理函数 + const debouncedUpdateContent = debounce(() => { // 过滤 xss topicData.content.value = DOMPurify.sanitize(editor.getHtml()) }, 1007) + + // 调用防抖处理函数,会在延迟时间内只执行一次更新操作 + debouncedUpdateContent() // 计算用户输入了多少个字符 textCount.value = editor.getText().trim().length } diff --git a/src/utils/debounce.ts b/src/utils/debounce.ts index a6a95f80..f2b8ba28 100644 --- a/src/utils/debounce.ts +++ b/src/utils/debounce.ts @@ -1,3 +1,6 @@ +/* + * 防抖函数,接受一个函数和一个延时时间 + */ export type DebouncedFunction any> = ( ...args: Parameters ) => void diff --git a/src/views/edit/Edit.vue b/src/views/edit/Edit.vue index c3d91063..6e939518 100644 --- a/src/views/edit/Edit.vue +++ b/src/views/edit/Edit.vue @@ -9,6 +9,9 @@ import KUNGalgameFooter from '@/components/KUNGalgameFooter.vue' import { useKUNGalgameEditStore } from '@/store/modules/edit' import { storeToRefs } from 'pinia' +// 导入防抖函数 +import { debounce } from '@/utils/debounce' + const topicData = storeToRefs(useKUNGalgameEditStore()) // 话题标题的文字 @@ -34,10 +37,14 @@ const handelInput = () => { return } - // 防抖 - setTimeout(() => { + // 创建一个防抖处理函数 + const debouncedInput = debounce(() => { + // 过滤 xss topicData.title.value = topicTitle.value - }, 1007) + }, 300) + + // 调用防抖处理函数,会在延迟时间内只执行一次更新操作 + debouncedInput() }