Refactor on useStyle api

pull/4186/head
mertsincan 2023-07-12 10:19:35 +01:00
parent 061febf1d4
commit 6f8e16f0ae
2 changed files with 13 additions and 11 deletions

View File

@ -12,6 +12,7 @@ export declare function useStyle(
options?: StyleOptions
): {
id: string;
name: string;
css: any;
unload: () => void;
load: () => void;

View File

@ -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,