vue中css样式动态添加
时间: 2023-09-28 16:07:17 浏览: 50
在Vue中可以通过以下方式动态添加CSS样式:
1. 使用v-bind绑定样式对象
可以使用v-bind指令将一个对象的属性绑定到一个CSS样式上。例如:
```
<template>
<div v-bind:style="myStyleObject">Hello World!</div>
</template>
<script>
export default {
data() {
return {
myStyleObject: {
color: 'red',
fontSize: '20px'
}
}
}
}
</script>
```
可以在Vue实例的data选项中定义一个样式对象,然后将其绑定到v-bind:style指令上。在这个例子中,样式对象包含两个属性color和fontSize,对应CSS样式中的color和font-size属性。
2. 使用计算属性
可以使用计算属性来动态计算CSS样式。例如:
```
<template>
<div v-bind:style="computedStyle">Hello World!</div>
</template>
<script>
export default {
data() {
return {
fontSize: 20
}
},
computed: {
computedStyle() {
return {
color: 'red',
fontSize: this.fontSize + 'px'
}
}
}
}
</script>
```
在这个例子中,我们定义了一个计算属性computedStyle,它返回一个包含color和fontSize属性的对象。fontSize属性是根据fontSize变量计算出来的,可以根据需要动态改变。
3. 使用class和style绑定
可以使用v-bind:class和v-bind:style指令来动态绑定class和style属性。例如:
```
<template>
<div v-bind:class="{ active: isActive }" v-bind:style="{ color: textColor }">Hello World!</div>
</template>
<script>
export default {
data() {
return {
isActive: true,
textColor: 'red'
}
}
}
</script>
```
在这个例子中,我们使用v-bind:class指令来动态绑定class属性,如果isActive变量为true,则添加active类。我们还使用v-bind:style指令来动态绑定color属性,值为textColor变量的值。