绑定内联样式
绑定对象
<template>
<!-- 在绑定 class 的时候不可以写驼峰,例如你 css类名为 is-active,那么绑定对象的key的名字就必须是 'is-active',但是绑定 style 时,你既可以写 fontSize 也可以写 font-size -->
<button
:style="{
color: 'red',
fontSize: `${size}px`,
'font-weight': 600
}"
>
按钮
</button>
</template>
<script setup>
import { ref } from 'vue'
const size = ref(20)
</script>
绑定响应式数据
<template>
<button
:style="[borderStyle, fontStyle, computedColorStyle]"
>
按钮
</button>
<!-- 或者 -->
<button
:style="{
...borderStyle,
...fontStyle,
...computedColorStyle
}"
>
按钮
</button>
</template>
<script setup>
import { ref, reactive } from 'vue'
const color = ref('red')
const borderStyle = ref({
border: 'none'
})
const fontStyle = reactive({
fontSize: '20px',
'font-weight': 600
})
const computedColorStyle = computed(() => ({
backgroundColor: 'tomato',
color: color.value
}))
</script>
绑定数组
我们还可以给
:style绑定一个包含多个样式对象的数组。这些对象会被合并后渲染到同一元素上
<template>
<div :style="[baseStyles, overridingStyles]"> 文字最终会是蓝色,粗体,20px </div>
</template>
<script setup>
import { ref } from 'vue'
const baseStyles = ref({
color: 'red',
fontSize: '20px'
})
const overridingStyles = ref({
color: 'blue',
'font-weight': 600
})
// 模版里合并style类似于
const array = [baseStyles.value, overridingStyles.value]
const finallyStyles = array.reduce((pre, cur) => {
return {
...pre,
...cur
}
}, {})
console.log(finallyStyles) // { color: 'blue', 'font-weight': 600, fontSize: '20px' }
</script>
自动前缀
当你在
:style中使用了需要浏览器特殊前缀的 CSS 属性时,Vue 会自动为他们加上相应的前缀。Vue 是在运行时检查该属性是否支持在当前浏览器中使用。如果浏览器不支持某个属性,那么将尝试加上各个浏览器特殊前缀,以找到哪一个是被支持的。
<template>
<button
:style="{
transition: 'all 4s ease'
}"
>
按钮
</button>
</template>
如果浏览器不支持 transition ,会自动添加以下前缀:
-webkit- 前缀
-webkit-transition: all 4s ease;
-moz- 前缀
-moz-transition: all 4s ease;
-ms- 前缀
-ms-transition: all 4s ease;
-o- 前缀
-o-transition: all 4s ease;
样式多值
数组仅会渲染浏览器支持的最后一个值
注意如果你的数组里面有多个元素,只要是最后一个元素被浏览器支持,即使前面还有其他被浏览器支持的元素,也只会渲染最后一个:
<template>
<div :style="{
fontSize: ['20px', '12px', 'red'],
}">
文字最终会是12px,
20px支持但不是最后一个,
10px不是数组最后一个元素,但是对于 font-size 来说,10px就是浏览器支持的最后一个值
</div>
</template>