[go: nahoru, domu]

Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(useCssVars): remove property on null/undefined #3821

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
feat(useCssVars): remove property on null/undefined
Signed-off-by: GitHub <noreply@github.com>
  • Loading branch information
ferferga committed Jun 21, 2024
commit fa63ae26a43f29f67eb916423b68a3c8b75a5a84
23 changes: 16 additions & 7 deletions packages/core/useCssVar/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,18 +25,18 @@ export interface UseCssVarOptions extends ConfigurableWindow {
* @param options
*/
export function useCssVar(
prop: MaybeRefOrGetter<string>,
prop: MaybeRefOrGetter<string | null | undefined>,
target?: MaybeElementRef,
options: UseCssVarOptions = {},
) {
const { window = defaultWindow, initialValue = '', observe = false } = options
const variable = ref(initialValue)
const { window = defaultWindow, initialValue, observe = false } = options
const variable = ref<string | null | undefined>(initialValue)
const elRef = computed(() => unrefElement(target) || window?.document?.documentElement)

function updateCssVar() {
const key = toValue(prop)
const el = toValue(elRef)
if (el && window) {
if (el && window && key) {
const value = window.getComputedStyle(el).getPropertyValue(key)?.trim()
variable.value = value || initialValue
}
Expand All @@ -51,15 +51,24 @@ export function useCssVar(

watch(
[elRef, () => toValue(prop)],
updateCssVar,
(_, old) => {
if (old[0] && old[1] && window)
window.getComputedStyle(old[0]).removeProperty(old[1])
updateCssVar()
},
{ immediate: true },
)

watch(
variable,
(val) => {
if (elRef.value?.style)
elRef.value.style.setProperty(toValue(prop), val)
const raw_prop = toValue(prop)
if (elRef.value?.style && raw_prop) {
if (val == null)
elRef.value.style.removeProperty(raw_prop)
else
elRef.value.style.setProperty(raw_prop, val)
}
},
)

Expand Down