0 day streak
javascript / expert
Snippet

Reactive CSS Variable Injection with v-bind

Vue allows direct binding of JavaScript state to CSS via v-bind() inside <style> blocks. Under the hood, Vue generates unique CSS variables on the component's root element and updates them whenever the reactive state changes. This provides a bridge between logic and presentation while maintaining high performance, as style recalculations are handled efficiently by the browser's CSS engine.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<script setup>
import { ref } from 'vue';
const themeColor = ref('#3498db');
const spacing = ref('20px');
</script>
<template>
<div class="dynamic-container">Content</div>
</template>
<style scoped>
.dynamic-container {
/* Vue compiles this into a CSS variable linked to the JS ref */
background-color: v-bind(themeColor);
padding: v-bind('spacing');
transition: background-color 0.3s ease;
}
</style>
vue
Breakdown
1
v-bind(themeColor)
Binds the reactive 'themeColor' ref to a dynamically generated CSS custom property.
2
v-bind('spacing')
String literals can also be used, allowing for more complex expressions if needed.