We can bind data to CSS inline style by style binding.
Version
Vue 2.6.11
Object
Hello World
is red, which is binding by data, not directly written by inline style.
<template>
<div :style="{ color }">Hello World</div>
</template>
<script>
export default {
data: _ => ({
color: 'red'
}),
}
</script>
Line 2
<div :style="{ color }">Hello World</div>
- Use
:style
to bind Object tostyle
attribute - We can use ES6 Object Shorthand to minimize Object
Line 7
data: _ => ({
color: 'red'
}),
Define color
property for style binding.
<template>
<div :style="red">Hello World</div>
</template>
<script>
export default {
data: _ => ({
red: {
color: 'red'
}
}),
}
</script>
Line 2
<div :style="red">Hello World</div>
We can also bind Object to style
attribute directly.
Line 7
data: _ => ({
red: {
color: 'red'
}
})
Define red
Object for style binding.
Array
Hello World
is not just red; its font size is bigger.
<template>
<div :style="[red, lg]">Hello World</div>
</template>
<script>
export default {
data: _ => ({
red: {
color: 'red'
},
lg: {
fontSize: '30px'
}
}),
}
</script>
Line 2
<div :style="[red, lg]">Hello World</div>
We can bind multiple Objects to style
attributes; just collect these Objects in Array.
Line 7
data: _ => ({
red: {
color: 'red'
},
lg: {
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