Vue(九):样式绑定v-bind示例

时间:2022-02-19 00:22:25

Vue.js class

class 与 style 是 HTML 元素的属性,用于设置元素的样式,我们可以用 v-bind 来设置样式属性。

Vue.js v-bind 在处理 class 和 style 时, 专门增强了它。表达式的结果类型除了字符串之外,还可以是对象或数组。

各种写法代码示例

<style>
.active {
width: 100px;
height: 30px;
background: #FFFACD;
}
.active1 {
background: #F0F8FF;
}
.styleWidth{
width: 200px;
}
.styleHeight{
height: 100px;
}
.styleColor{
background: #FAF0E6;
}
.computedStyle{
width: 210px;
height: 30px;
background: #CAFACD;
}
.arrayStyle1{
width: 180px;
height: 30px;
}
.arrayStyle2{
background: #FAFCAA;
}
.arrayStyle3{
background: #DAFAFF;
}
</style>
</head>
<body>
<div id="app">
<!-- 样式绑定 -->
<div v-bind:class="{active:isActive}">样式绑定</div>
<!-- 样式覆盖 -->
<div v-bind:class="{active:isActive, active1:isActive1}">样式覆盖</div>
<!-- 绑定数据对象 -->
<div v-bind:class="styleA">绑定数据对象</div>
<!-- 绑定返回对象的计算属性 -->
<div v-bind:class="styleB">绑定返回对象的计算属性</div> <!-- 数组语法 -->
<div v-bind:class="[arrayStyle1,arrayStyle2]">数组语法</div>
<!-- 使用三元表达式切换属性 -->
<div v-bind:class="[arrayStyle1, isActive?arrayStyle3:'']">使用三元表达式切换属性</div> <!-- 内联样式,注意v-bind是style,不是class了 -->
<div v-bind:style="{width: neilian.width + 'px' ,height: neilian.height + 'px' ,background: neilian.bgcolor}">内联样式</div>
<!-- 内联直接绑定到样式对象 -->
<div v-bind:style="neilian2">内联直接绑定到样式对象</div>
<!-- 内联使用数组将多个样式对象绑定到一个元素上 -->
<div v-bind:style="[neilian2,neilian3]">内联使用数组将多个样式对象绑定到一个元素上</div> <!-- 注意:当 v-bind:style 使用需要特定前缀的 CSS 属性时,如 transform ,Vue.js 会自动侦测并添加相应的前缀。-->
</div> <script>
new Vue({
el: '#app',
data: {
neilian:{
width:280,
height:25,
bgcolor:"#DFFACD"
},
neilian2:{
width:"260PX",
fontSize:'20px'
},
neilian3:{
background: "#CAFACD",
},
arrayStyle1:"arrayStyle1",
arrayStyle2:"arrayStyle2",
arrayStyle3:"arrayStyle3",
isActive: true,
isActive1: true,
styleA:{
styleWidth:true,
styleHeight:true,
styleColor:true
},
msg:{
error:true,
isuse:0
}, },
computed:{
styleB:function(){
return{
computedStyle:this.msg.error && this.msg.isuse==0
}
}
}
})
</script>
</body>

运行结果

Vue(九):样式绑定v-bind示例