From 6f8e16f0aece70f988d588afe3316e73c6e6b117 Mon Sep 17 00:00:00 2001 From: mertsincan Date: Wed, 12 Jul 2023 10:19:35 +0100 Subject: [PATCH] Refactor on useStyle api --- components/lib/usestyle/UseStyle.d.ts | 1 + components/lib/usestyle/UseStyle.js | 23 ++++++++++++----------- 2 files changed, 13 insertions(+), 11 deletions(-) diff --git a/components/lib/usestyle/UseStyle.d.ts b/components/lib/usestyle/UseStyle.d.ts index d0111f07d..7c9bf8f6c 100644 --- a/components/lib/usestyle/UseStyle.d.ts +++ b/components/lib/usestyle/UseStyle.d.ts @@ -12,6 +12,7 @@ export declare function useStyle( options?: StyleOptions ): { id: string; + name: string; css: any; unload: () => void; load: () => void; diff --git a/components/lib/usestyle/UseStyle.js b/components/lib/usestyle/UseStyle.js index 94ceda23f..d96b1519b 100644 --- a/components/lib/usestyle/UseStyle.js +++ b/components/lib/usestyle/UseStyle.js @@ -15,25 +15,25 @@ let _id = 0; export function useStyle(css, options = {}) { const isLoaded = ref(false); + const cssRef = ref(css); + const styleRef = ref(null); const defaultDocument = DomHandler.isClient() ? window.document : undefined; const { document = defaultDocument, immediate = true, manual = false, name = `style_${++_id}`, id = undefined, media = undefined } = options; - const cssRef = ref(css); - let stop = () => {}; const load = () => { if (!document) return; - const el = document.querySelector(`style[data-primevue-style-id="${name}"]`) || document.getElementById(id) || document.createElement('style'); + styleRef.value = document.querySelector(`style[data-primevue-style-id="${name}"]`) || document.getElementById(id) || document.createElement('style'); - if (!el.isConnected) { - el.type = 'text/css'; - id && (el.id = id); - media && (el.media = media); - document.head.appendChild(el); - name && el.setAttribute('data-primevue-style-id', name); + if (!styleRef.value.isConnected) { + styleRef.value.type = 'text/css'; + id && (styleRef.value.id = id); + media && (styleRef.value.media = media); + document.head.appendChild(styleRef.value); + name && styleRef.value.setAttribute('data-primevue-style-id', name); } if (isLoaded.value) return; @@ -41,7 +41,7 @@ export function useStyle(css, options = {}) { stop = watch( cssRef, (value) => { - el.textContent = value; + styleRef.value.textContent = value; }, { immediate: true } ); @@ -52,7 +52,7 @@ export function useStyle(css, options = {}) { const unload = () => { if (!document || !isLoaded.value) return; stop(); - document.head.removeChild(document.getElementById(id)); + DomHandler.isExist(styleRef.value) && document.head.removeChild(styleRef.value); isLoaded.value = false; }; @@ -63,6 +63,7 @@ export function useStyle(css, options = {}) { return { id, + name, css: cssRef, unload, load,