Skip to content

Commit fe19c74

Browse files
authoredJul 17, 2024··
feat(useCssVars): remove property on null/undefined (#3821)
Signed-off-by: GitHub <noreply@github.com>
1 parent efe4df8 commit fe19c74

File tree

2 files changed

+28
-7
lines changed

2 files changed

+28
-7
lines changed
 

‎packages/core/useCssVar/index.test.ts

+12
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,18 @@ describe('useCssVar', () => {
1616
expect(variable.value).toBe('red')
1717
})
1818

19+
it('should handle null and undefined', () => {
20+
const el = document.createElement('div')
21+
const property = '---color'
22+
const variable = useCssVar(property, el)
23+
24+
expect(window?.getComputedStyle(el).getPropertyValue('--color')).toBe('')
25+
variable.value = 'red'
26+
setTimeout(() => {
27+
expect(window?.getComputedStyle(el).getPropertyValue('--color')).toBe('red')
28+
}, 100)
29+
})
30+
1931
it('should work observe', async () => {
2032
const window = defaultWindow
2133
const el = document.createElement('div')

‎packages/core/useCssVar/index.ts

+16-7
Original file line numberDiff line numberDiff line change
@@ -25,18 +25,18 @@ export interface UseCssVarOptions extends ConfigurableWindow {
2525
* @param options
2626
*/
2727
export function useCssVar(
28-
prop: MaybeRefOrGetter<string>,
28+
prop: MaybeRefOrGetter<string | null | undefined>,
2929
target?: MaybeElementRef,
3030
options: UseCssVarOptions = {},
3131
) {
32-
const { window = defaultWindow, initialValue = '', observe = false } = options
33-
const variable = ref(initialValue)
32+
const { window = defaultWindow, initialValue, observe = false } = options
33+
const variable = ref<string | null | undefined>(initialValue)
3434
const elRef = computed(() => unrefElement(target) || window?.document?.documentElement)
3535

3636
function updateCssVar() {
3737
const key = toValue(prop)
3838
const el = toValue(elRef)
39-
if (el && window) {
39+
if (el && window && key) {
4040
const value = window.getComputedStyle(el).getPropertyValue(key)?.trim()
4141
variable.value = value || initialValue
4242
}
@@ -51,15 +51,24 @@ export function useCssVar(
5151

5252
watch(
5353
[elRef, () => toValue(prop)],
54-
updateCssVar,
54+
(_, old) => {
55+
if (old[0] && old[1] && window)
56+
window.getComputedStyle(old[0]).removeProperty(old[1])
Has conversations. Original line has conversations.
57+
updateCssVar()
58+
},
5559
{ immediate: true },
5660
)
5761

5862
watch(
5963
variable,
6064
(val) => {
61-
if (elRef.value?.style)
62-
elRef.value.style.setProperty(toValue(prop), val)
65+
const raw_prop = toValue(prop)
66+
if (elRef.value?.style && raw_prop) {
67+
if (val == null)
68+
elRef.value.style.removeProperty(raw_prop)
69+
else
70+
elRef.value.style.setProperty(raw_prop, val)
71+
}
6372
},
6473
)
6574

0 commit comments

Comments
 (0)
Please sign in to comment.