在 Vue 中,你可以使用 v-bind
指令来动态绑定一个 style 对象到元素的 style
属性。例如:
<template>
<div v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }">
这是一个动态样式的例子
</div>
</template>
<script>
export default {
data() {
return {
activeColor: 'red',
fontSize: 30
}
}
}
</script>
你也可以在一个样式对象中定义多个样式属性,例如:
<template>
<div v-bind:style="{ color: activeColor, fontSize: fontSize + 'px', fontWeight: 'bold' }">
这是一个动态样式的例子
</div>
</template>
<script>
export default {
data() {
return {
activeColor: 'red',
fontSize: 30
}
}
}
</script>
你还可以使用计算属性来动态计算样式对象,例如:
<template>
<div v-bind:style="styleObject">
这是一个动态样式的例子
</div>
</template>
<script>
export default {
data() {
return {
activeColor: 'red',
fontSize: 30
}
},
computed: {
styleObject: function() {
return {
color: this.activeColor,
fontSize: this.fontSize + 'px',
fontWeight: 'bold'
}
}
}
}
</script>
希望这些示例能够帮助你。