4.3.3 绑定内联样式
使用 v-bind:style(即 :style)可以给元素绑定内联样式,方法与 :class 类似。也存在对象语法和数组语法,看起来很像在元素上直接写 css。
在 components 文件夹下新建 BindStyle.vue 组件,写入如示例 11 所示代码,并在路由 index.js 中进行配置。
示例 11
App.vue
<template>
<HzhBindStyle>黄子涵</HzhBindStyle>
</template>
<script>
import HzhBindStyle from './components/hzhBindStyle.vue';
export default {
name: 'APP',
data() {
return {
};
},
components: {
HzhBindStyle,
}
};
</script>
<style scoped>
.static {
margin: 5px 0;
font-size: 20px;
}
.active {
text-align: center;
width: 60px;
border: 1px solid #000;
}
.danger {
background: #ff0;
}
</style>
HzhBindStyle.vue
<template>
<div :style="{ border: activeColor, fontSize: fontSize + 'px'}">黄子涵:绑定内联样式</div>
</template>
<script>
export default {
name: 'HzhBindStyle',
data() {
return {
activeColor: "1px solid #000",
fontSize: 22
};
}
};
</script>
<style>
</style>
在浏览器中运行,显示效果和渲染结果如下图所示。
大多数情况下,直接写一长串的样式不便于阅读和维护,因此实际的开发中往往是写在 data 或者computed 计算属性里。下面以 data 的形式来改写示例 11,代码如下所示。
<template>
<div :style="styles">黄子涵:绑定内联样式</div>
</template>
<script>
export default {
name: 'HzhBindStyle',
data() {
return {
styles: {
width: 220 + 'px',
border: '1px solid #000',
fontSize: 22 + 'px'
}
};
}
};
</script>
<style>
</style>
在使用 :style 时,Vue.js 会自动给特殊的 css 属性名称增加前缀,比如 transform 属性 。