样式绑定
1、class样式处理
对象语法
<div v-bind:class="{active: isActive, bg: isBg}">测试内容</div> <script src="../js/vue.js"></script> <script> var vm = new Vue({ el: '#app', data: { isActive: true,
isBg: true }, methods: { handle: function() { this.isActive = !this.isActive; } } }) </script>
数组语法
<div v-bind:class="[activeClass, bgClass]">测试内容2</div>
<button @click="handle1">切换</button>
<script src="../js/vue.js"></script>
<script>
var vm = new Vue({
el: '#app',
data: {
activeClass: 'active',
bgClass: 'bg'
},
methods: {
handle1: function() {
this.activeClass = '';
this.bgClass = '';
}
}
})
</script>
样式绑定使用:
(1)对象绑定与数组绑定可以结合使用
<div v-bind:class="[activeClass, bgClass, {error: iserroe}]">测试内容2</div>
(2)class绑定的值可以简化操作
<div v-bind:class="arrClasses">测试内容3</div> <div v-bind:class="objClasses">测试内容5</div> <script src="../js/vue.js"></script> <script> var vm = new Vue({ el: '#app', data: { arrClasses: ['active', 'bg'], objClasses: { active: true, bg: true } } }) </script>
(3)默认的class会保留
<div class="base" v-bind:class="arrClasses">测试内容4</div>
2、style样式处理
对象语法
<div v-bind:style="{border: borderStyle, width: widthStyle, height: heightStyle}"></div>
<div v-bind:style="objStyle"></div> <script src="../js/vue.js"></script> <script> var vm = new Vue({ el: '#app', data: { borderStyle: '1px solid pink', widthStyle: '100px', heightStyle: '200px,
objStyle: {
backgroundColor: 'purple',
color: '20px'
} } }) </script>
数组语法
如果样式相同,后面的样式会覆盖掉前面的样式
<div v-bind:Style="[objStyle, arrStyle]"></div>
<script src="../js/vue.js"></script>
<script>
var vm = new Vue({
el: '#app',
data: {
objStyle: {
border: '1px solid purple',
width: '200px',
height: '100px'
},
arrStyle: {
border: '5px solid orange',
backgroundColor: 'pink'
}
}
})
</script>