JAVASCRIPT
Dynamic CSS Styling with `v-bind()` in Vue 3 Scoped Styles
Enhance your Vue 3 components by dynamically binding JavaScript variables to CSS properties directly within your `<style scoped>` blocks using `v-bind()`.
// DynamicStyledComponent.vue
<template>
<div class="dynamic-box" :style="{ '--box-size': boxSize + 'px' }">
<p>Box Size: {{ boxSize }}px</p>
<button @click="increaseSize">Increase Size</button>
<button @click="decreaseSize">Decrease Size</button>
</div>
</template>
<script setup>
import { ref } from 'vue';
const boxSize = ref(100);
const boxColor = ref('lightblue');
const increaseSize = () => {
boxSize.value += 10;
};
const decreaseSize = () => {
boxSize.value = Math.max(50, boxSize.value - 10);
};
</script>
<style scoped>
.dynamic-box {
width: v-bind(boxSize + 'px'); /* Direct binding */
height: v-bind('boxSize + "px"'); /* Quoted string for complex expressions */
background-color: v-bind(boxColor);
border: 2px solid darkblue;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
margin-top: 20px;
}
</style>
How it works: This snippet demonstrates how to use Vue 3's `v-bind()` feature within `<style scoped>` blocks to create dynamic CSS. It allows you to bind reactive JavaScript variables, like `boxSize` and `boxColor`, directly to CSS properties. As the `boxSize` and `boxColor` reactive references change, the component's styles update automatically, offering a powerful way to control appearance programmatically.