我们可以使用v-bind语法来拓展样式的绑定,例如做一些简单的样式切换及元素计算等等。
Style样式绑定,也是有多种语法的,包括对象语法、数组语法。
对象语法
v-bind:style
的对象语法十分直观,看着非常像 CSS,但其实是一个 JavaScript 对象。CSS 样式名可以用驼峰式 (camelCase) 或短横线分隔 (kebab-case,记得用引号括起来) 来命名。
实例演示
<template>
<div>
<!-- 单独绑定样式 -->
<h1 :style="{ color: fontColorRed, fontSize: fontSize + 'px' }">hello world!!!</h1>
<!-- 绑定一个样式对象 -->
<h1 :style="styleObject">hello world!!!</h1>
</div>
</template>
<script>
export default {
data () {
return {
fontColorRed: 'red',
fontSize: 100,
styleObject: {
color: 'blue',
fontSize: '100px'
}
}
}
}
</script>
数组对象
v-bind:style
的数组语法可以将多个样式对象应用到同一个元素上:
<template>
<div>
<h1 :style="[styleObject, {fontSize: '100px'}]">hello world</h1>
</div>
</template>
<script>
export default {
data () {
return {
styleObject: {
color: 'red',
fontWeight: 100
}
}
}
}
</script>