vue3动态样式
时间: 2023-07-01 11:18:23 浏览: 50
Vue3 中可以使用 `:style` 指令来绑定动态样式,例如:
```html
<template>
<div :style="{ color: textColor, fontSize: textSize + 'px' }">Hello, World!</div>
</template>
<script>
export default {
data() {
return {
textColor: 'red',
textSize: 16
}
}
}
</script>
```
在上面的示例中,`textColor` 和 `textSize` 都是响应式数据。通过 `:style` 指令可以将这些数据与具体的样式属性绑定,实现动态样式效果。
除了纯粹的样式属性,我们还可以使用对象语法和数组语法来绑定动态样式,例如:
```html
<template>
<div :style="styleObject">Hello, World!</div>
<div :style="[styleObject, { fontSize: textSize + 'px' }]">Hello, World!</div>
</template>
<script>
export default {
data() {
return {
styleObject: {
color: 'red',
fontWeight: 'bold'
},
textSize: 16
}
}
}
</script>
```
在上面的示例中,`styleObject` 是一个包含样式属性的对象,通过 `:style` 指令可以将其与元素绑定。另外,我们还可以通过数组语法将多个样式对象合并到一起,实现更为灵活的动态样式绑定。