From 618b4465f4eac6ae37a925b7bc16b397b684a707 Mon Sep 17 00:00:00 2001 From: motea927 Date: Tue, 13 Jun 2023 21:28:07 +0800 Subject: [PATCH] feat: use reactivity value --- packages/core/directive.ts | 46 +++++++++++++++++++++++++------------- 1 file changed, 30 insertions(+), 16 deletions(-) diff --git a/packages/core/directive.ts b/packages/core/directive.ts index cafc17b..014cc29 100644 --- a/packages/core/directive.ts +++ b/packages/core/directive.ts @@ -1,4 +1,5 @@ import type { Directive } from 'vue' +import { watchEffect } from 'vue' import type { BindingObj, Options } from './shared' import { getDefaultString, @@ -14,25 +15,38 @@ export type SafeHtmlDirective = Directive< string | (() => string) | BindingObj > -export const vSafeHtml: SafeHtmlDirective = (el, binding) => { - if (!binding.value) return +const stopWatchMap = new WeakMap void>() - const bindingValue = getBindingValue(binding.value) - const defaultString = - typeof binding.value === 'string' || typeof binding.value === 'function' - ? getDefaultString() - : getDefaultString(binding.value.defaultString) - const sanitizeConfig = - typeof binding.value === 'string' || typeof binding.value === 'function' - ? undefined - : binding.value.sanitizeConfig +export const vSafeHtml: SafeHtmlDirective = { + beforeMount(el, binding) { + const stopWatch = watchEffect(() => { + if (!binding.value) return - if (handleDefaultString(el, bindingValue, defaultString, sanitizeConfig)) { - return - } + const bindingValue = getBindingValue(binding.value) + const defaultString = + typeof binding.value === 'string' || typeof binding.value === 'function' + ? getDefaultString() + : getDefaultString(binding.value.defaultString) + const sanitizeConfig = + typeof binding.value === 'string' || typeof binding.value === 'function' + ? undefined + : binding.value.sanitizeConfig + + if ( + handleDefaultString(el, bindingValue, defaultString, sanitizeConfig) + ) { + return + } - const sanitizeResult = sanitizeHtml(bindingValue, sanitizeConfig) - el.innerHTML = sanitizeResult + const sanitizeResult = sanitizeHtml(bindingValue, sanitizeConfig) + el.innerHTML = sanitizeResult + }) + stopWatchMap.set(el, stopWatch) + }, + beforeUnmount(el) { + stopWatchMap.get(el)?.() + stopWatchMap.delete(el) + } } export const createDirective = (options?: Options) => {