在 Vue 中,可以使用 v-bind:style 或者简写的:style 来动态绑定样式。这两种方式可以实现绑定行内样式的需求。
其中,:style 的属性值为一个对象,该对象的 key 为 CSS 属性名,value 为对应的属性值,如下所示:
html
<template>
<div :style="{ backgroundColor: bg_color, color: font_color }">Hello World!</div>
</template>
<script>
export default {
data() {
return {
bg_color: 'red',
font_color: 'white'
}
}
}
</script>
在上述代码中,使用 :style 绑定 div 元素的样式,绑定的属性为 backgroundColor 和 color,它们的值分别为 bg_color 和 font_color,它们的值来自 Vue 实例的数据。
除了绑定对象方式外,还可以使用动态绑定取值的方式,如下所示:
html
<template>
<div :style="styleObject"></div>
</template>
<script>
export default {
data() {
return {
styleObject: {
backgroundColor: 'red',
color: 'white'
}
}
},
mounted() {
this.styleObject.backgroundColor = 'blue'
}
}
</script>
在上述代码中,使用 :style 绑定 div 元素的样式,绑定的属性值使用如下方式:
- 在 data 中定义了一个名为
styleObject 的对象,并设置初始值;
- 在 mounted 生命周期钩子中,修改
styleObject 对象中 backgroundColor 属性的值;
这样,在 mounted 生命周期钩子中,修改 styleObject 对象中 backgroundColor 属性的值之后,该值会自动更新到绑定的元素上。
此外,除了绑定对象外,绑定样式的单个属性值也可以是一个计算属性或者是在 methods 中定义了一个返回样式的函数,动态计算样式的值然后绑定,如下所示:
html
<template>
<div :style="{ backgroundColor: computedBgColor }"></div>
</template>
<script>
export default {
data() {
return {
isActive: true,
color1: 'red',
color2: 'green'
}
},
computed: {
computedBgColor() {
return this.isActive ? this.color1 : this.color2;
}
}
}
</script>
在上述代码中,使用 computedBgColor 计算属性,并动态计算出参数,设置绑定的样式值。当 isActive 变量的值为 true 时,computedBgColor 计算属性的值为 color1 的值,否则为 color2 的值。