@@ -25,18 +25,18 @@ export interface UseCssVarOptions extends ConfigurableWindow {
2525 * @param options
2626 */
2727export 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 ] )
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