模板语法–3.6样式绑定
1.class样式处理
-
对象语法
<div v-bind:class="{active:isActive,error:isError}">
基本用法:用v-bind操作属性,绑定class属性,值通过对象的方式控制类名是否显示,多个类名用对象分开。
-
数组语法
<div v-bind:class="[activeClass,errorClass]">测试样式2</div>
用法:定义相关的属性,值对应类名,最终类名能渲染.
样式绑定相关的语法细节:
1、对象绑定和数组绑定可以结合使用
2、class绑定的值可以简化操作
3、默认的class如何处理?
默认的样式将会保留 class 和绑定的样式一块存在。
<!DOCTYPE html>
<html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml" xmlns:v-on="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>样式绑定</title>
<style type="text/css">
.active{
border: 1px solid red;
width: 100px;
height:100px
}
.error{
background-color: orange;
}
.test{
color: red;
}
.base{
font-size: 28px;
}
</style>
</head>
<body>
<div id="app">
<div v-bind:class="{active:isActive,error:isError}">
测试样式
</div>
<button v-on:click="handle">控制样式</button>
<div v-bind:class="[activeClass,errorClass,{test:isTest}]">测试样式2</div>
<button v-on:click="handle2">控制样式二</button>
<button v-on:click="handle3">控制样式三</button>
<div v-bind:class="arrClasses"></div>
<div v-bind:class="objClasses"></div>
<button v-on:click="handle4">控制样式四</button>
<div class="base" v-bind:class="objClasses"></div>
<!--默认的会保留-->
</div>
<script type="text/javascript" src="vue.js"></script>
<script>
var vm = new Vue({
el:'#app',
data:{
isActive:true,
isError:true,
activeClass:'active'
,errorClass:'error',
isTest:true,
arrClasses:['active','error'],
objClasses:{
active:true,
error:true,
}
},
methods:{
handle:function () {
//控制isActive的值在true和false切换
this.isActive = !this.isActive;
this.isError = !this.isError;
},
handle2:function () {
//应用 给div加几个类名,去掉一个直接置空,如果显示需要接着重置
this.activeClass = '',
this.errorClass = ''
},
handle3:function () {
this.isTest = !this.isTest
},
handle4:function () {
this.objClasses.error = false;
}
}
})
</script>
</body>
</html>
2.style内联样式处理
-
对象语法
<div v-bind:style="{border:borderStyle,width:widthStyle,height:heightStyle}"></div>
-
数组语法
<div v-bind:style="[objStyle,overrideStyle]"></div>
model:
<!DOCTYPE html>
<html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml" xmlns:v-on="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>内联样式</title>
</head>
<body>
<div id="app">
<div v-bind:style="{border:borderStyle,width:widthStyle,height:heightStyle}"></div>
<button v-on:click="handle">切换</button>
<div v-bind:style="objStyle"></div>
<div v-bind:style="[objStyle,overrideStyle]"></div>
</div>
<script type="text/javascript" src="vue.js"></script>
<script>
var vm = new Vue({
el:'#app',
data:{
borderStyle: '1px solid blue'
,widthStyle: '100px'
,heightStyle: '200px'
,objStyle:{
border: '1px solid green'
,width: '200px'
,height: '100px'
}
,overrideStyle:{
border: '5px solid orange'
,background: 'blue'
}
},
methods:{
handle:function () {
this.heightStyle = '100px'
this.objStyle.width = "100px"
}
},
})
</script>
</body>
</html>