SFC - undefined css vars
Version
3.0.2
Reproduction link
https://codepen.io/talmand/pen/8d7aa90123720c03f09d83f542b34666
Steps to reproduce
Attempt to use a reference to a var that doesn't exist or returns anything but a string.
<template>
<div class="text">hello</div>
</template>
<script>
export default {
data() {
return {
color: 'red'
}
}
}
</script>
<style vars="{ color, bgcolor }">
.text {
background-color: var(--bgcolor, gainsboro);
color: var(--color);
}
</style>
In the CodePen example, inspect the template's div to see that --bgcolor has "undefined" as its value and prevents the fallback value from being used.
What is expected?
If the injection involves anything other than a string it should skip over creating that CSS var to allow for a possible fallback of the CSS var() function to work.
What is actually happening?
If the var being referenced doesn't actually exist then the CSS var is created as --color: undefined
, which prevents the CSS var() function fallback from being used. If the var returns anything but a string then that value is used, such as --color: [object Object]
.
I do have a thought to fix this by adding a type check for strings within "useCssVars.ts" before the setProperty is used to create the CSS vars in the style attribute. It could also possibly allow for a console warning to state what the issue for that particular CSS var. The code I've written to address this works in my quick browser tests, although a proper test is difficult because it requires forcing errors in "useCssVars.spec.ts" which TypeScript obviously wouldn't care for.
Although, I'm not fully convinced this problem needs fixing because of two reasons. Requiring a string doesn't change an invalid value provided to the CSS var still prevents the fallback from working. I also found not using an inline object in the style block's vars attribute in favor of an object I create in the component is far more flexible. In that situation if there's no reference for a CSS var in my object then there's no var created in the style attribute. Thus the fallback of the CSS var() function works.
Another answer is simply, "don't do that".
But it should be a reasonably easy contribution to the project so I decided to inquire if there's any interest.
I'm not sure at this moment. Shortly after this issue was opened and a PR created the syntax and some of the functionality of the feature changed. So I closed the PR until these changes were more locked down. At this point I wouldn't be against closing the issue to reopen later if it something of this nature still persists.