We can bind data to CSS inline style by style binding.
Version
Vue 3.2
Object
Hello World
is red, which is binding by data, not directly written by inline style.
<script setup>
let color = $ref ('red')
</script>
<template>
<div :style="{ color }">Hello World</div>
</template>
Line 6
<div :style="{ color }">Hello World</div>
- Use
:style
to bind Object tostyle
attribute - We can use ES6 Object Shorthand to minimize Object
Line 2
let color = $ref ('red')
Define color
reactive variable for style binding.
<script setup>
let red = $ref ({ color: 'red' })
</script>
<template>
<div :style="red">Hello World</div>
</template>
Line 6
<div :style="red">Hello World</div>
We can also bind Object to style
attribute directly.
Line 2
let red = $ref ({ color: 'red' })
Define red
Object by reactive variable for style binding.
Array
Hello World
is not just red; its font size is bigger.
<script setup>
let red = $ref ({ color: 'red' })
let lg = $ref ({ fontSize: '30px' })
</script>
<template>
<div :style="[red, lg]">Hello World</div>
</template>
Line 6
<div :style="[red, lg]">Hello World</div>
We can bind multiple Objects to style
attributes; just collect these Objects in Array.
Line 2
let red = $ref ({ color: 'red' })
let lg = $ref ({ fontSize: '30px' })
Define multiple Objects for style binding.
Conclusion
- If we want to change CSS style at runtime, we can use style binding by JavaScript