Skip to content

Commit

Permalink
feat(useCssVar): support prop be ref (vitest-dev#1236)
Browse files Browse the repository at this point in the history
Co-authored-by: Jelf <353742991@qq.com>
  • Loading branch information
btea and okxiaoliang4 committed Feb 13, 2022
1 parent 7b40091 commit f99ea0d
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 5 deletions.
16 changes: 16 additions & 0 deletions packages/core/useCssVar/demo.vue
Expand Up @@ -11,6 +11,16 @@ const switchColor = () => {
else
color.value = '#df8543'
}
const elv = ref(null)
const key = ref('--color')
const colorVal = useCssVar(key, elv)
const changeVar = () => {
if (key.value === '--color')
key.value = '--color-one'
else
key.value = '--color'
}
</script>

<template>
Expand All @@ -20,4 +30,10 @@ const switchColor = () => {
<button @click="switchColor">
Change Color
</button>
<div ref="elv" style="--color: #7fa998; --color-one: #df8543;" :style="{color: colorVal}">
Sample text, {{ key }}: {{ colorVal }}
</div>
<button style="margin-left: 0;" @click="changeVar">
Change Color Variable
</button>
</template>
4 changes: 4 additions & 0 deletions packages/core/useCssVar/index.md
Expand Up @@ -13,4 +13,8 @@ import { useCssVar } from '@vueuse/core'

const el = ref(null)
const color = useCssVar('--color', el)

const elv = ref(null)
const key = ref('--color')
const colorVal = useCssVar(key, elv)
```
11 changes: 6 additions & 5 deletions packages/core/useCssVar/index.ts
@@ -1,4 +1,5 @@
import { computed, ref, watch } from 'vue-demi'
import { computed, ref, unref, watch } from 'vue-demi'
import type { MaybeRef } from '@vueuse/shared'
import type { ConfigurableWindow } from '../_configurable'
import { defaultWindow } from '../_configurable'
import type { MaybeElementRef } from '../unrefElement'
Expand All @@ -13,16 +14,16 @@ import { unrefElement } from '../unrefElement'
* @param options
*/
export function useCssVar(
prop: string,
prop: MaybeRef<string>,
target?: MaybeElementRef,
{ window = defaultWindow }: ConfigurableWindow = {},
) {
const variable = ref('')
const elRef = computed(() => unrefElement(target) || window?.document?.documentElement)

watch(
elRef,
(el) => {
[elRef, () => unref(prop)],
([el, prop]) => {
if (el && window)
variable.value = window.getComputedStyle(el).getPropertyValue(prop)
},
Expand All @@ -33,7 +34,7 @@ export function useCssVar(
variable,
(val) => {
if (elRef.value?.style)
elRef.value.style.setProperty(prop, val)
elRef.value.style.setProperty(unref(prop), val)
},
)

Expand Down

0 comments on commit f99ea0d

Please sign in to comment.