feat: Support default values for v-bind in CSS
The default value is defined by an SCSS variable. If the JavaScript variable is null, I want to use the SCSS variable as the fallback.
I don't want to use :export and import in all components
// variable.scss in library
$theme-color: blue !default; // can be overridden in the project if needed
<script setup>
defineProps({
color: {
color: String,
default: null,
}
})
</script>
<style>
.mm {
color: v-bind(color, $theme-color)
}
</style>
wiill be transfromed to var(--var-name, $theme-color)
--var-name will be a hashed name, and $theme-color will hold the value assigned to $theme-color.
There hasn't been an RFC for this change. While I understand that it is a relatively small change, I do worry that we may miss out on feedback from the community without an RFC.
I read through the original RFC for v-bind in <style>. The use case described here doesn't seem to be discussed, but I did find two comments that seemed relevant:
- https://github.com/vuejs/rfcs/pull/231#issuecomment-735514908 - This comment discusses passing a default to
v-bind, but it treats the default as a JS expression. That use case can easily be addressed in other ways (see Evan's response) and it doesn't take account of using the default with pre-processors. - https://github.com/vuejs/rfcs/pull/231#issuecomment-790061235 - This proposes adding a second parameter to
v-bindfor a different purpose. I don't agree with that proposal, but I think it's important to acknowledge that adding a second parameter tov-bindis something we can only do once, so we need to be sure it's the best use for it.
Another comment notes a potential workaround:
--myColor: v-bind('myReactiveColor');
color: var(--myColor, black);
This does appear to work (Playground) and I believe it would be compatible with pre-processors.
As for the implementation in this PR, I worry about backwards compatibility. Commas could already appear in expressions for other reasons, e.g.:
Of course the code can be fixed, but I think it illustrates that 'working' code could potentially be broken by this change.
@skirtles-code
Thank you for your response and suggestions. I hadn't used v-bind like v-bind(['red', 'blue'][value]) before; I had always used the quoted form v-bind('[red, blue][value]'), so I didn't consider the case with the comma in the expression. I still believe that having v-bind support default values would be beneficial, so I have resubmitted the code. If the maintenance team feels that it's not suitable to add this feature at this time, You can close this PR or I will do it.