vue3中如何实现一个标签的style点击之后实现改变
时间: 2024-03-09 13:45:17 浏览: 23
在 Vue 3 中,你可以使用`v-bind:style`或`:style`来绑定一个动态的样式对象。然后在点击事件中,可以更新这个样式对象中的属性,从而实现标签的样式改变。
以下是一个简单的示例代码:
```html
<template>
<div :style="tagStyle" @click="changeStyle">
点我改变样式
</div>
</template>
<script>
import { reactive } from 'vue';
export default {
setup() {
const tagStyle = reactive({
backgroundColor: 'blue',
color: 'white',
padding: '10px',
borderRadius: '5px',
cursor: 'pointer',
});
function changeStyle() {
tagStyle.backgroundColor = 'red';
tagStyle.color = 'black';
}
return {
tagStyle,
changeStyle,
};
},
};
</script>
```
在上面的代码中,我们使用了 `reactive` 函数来创建了一个响应式的 `tagStyle` 对象,它包含了标签的初始样式。然后,在 `changeStyle` 方法中,我们更新了这个对象中的 `backgroundColor` 和 `color` 属性,从而实现了标签样式的改变。最后,在模板中,我们使用 `:style` 来绑定这个样式对象,`@click` 来监听点击事件并调用 `changeStyle` 方法。