vue点击事件修改css样式
时间: 2023-09-21 16:11:06 浏览: 62
可以使用Vue中的绑定语法以及对象语法来实现点击事件修改CSS样式。
1. 绑定语法
在Vue模板中使用v-bind指令来绑定样式对象,然后在点击事件中修改该对象的属性值。
```
<template>
<div :style="styleObj" @click="changeStyle"></div>
</template>
<script>
export default {
data() {
return {
styleObj: {
backgroundColor: 'red',
fontSize: '16px'
}
}
},
methods: {
changeStyle() {
this.styleObj.backgroundColor = 'blue';
this.styleObj.fontSize = '20px';
}
}
}
</script>
```
2. 对象语法
在Vue模板中使用对象语法,直接在点击事件中修改CSS样式。
```
<template>
<div :style="{ backgroundColor: bgColor, fontSize: fontSize }" @click="changeStyle"></div>
</template>
<script>
export default {
data() {
return {
bgColor: 'red',
fontSize: '16px'
}
},
methods: {
changeStyle() {
this.bgColor = 'blue';
this.fontSize = '20px';
}
}
}
</script>
```
以上两种方法都可以实现动态修改CSS样式。