動態綁定style和class
數據綁定一個常見需求是操作元素的 class 列表和它的內聯樣式。因為它們都是屬性 ,我們可以用v-bind 處理它們:只需要計算出表達式最終的字符串。而且,把 v-bind 用于 class 和 style 時,表達式的結果類型除了字符串之外,還可以是對象或數組。
案例代碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.test{
width: 200px;
height: 50px;
background-color: red;
}
.active{
width: 300px;
height: 150px;
background-color: green;
color: white;
font-size: 25px;
}
</style>
</head>
<body>
<div id="app">
<p class="test" :class="{active : isActive}">動態綁定class</p>
<p :style="currentStyle">動態綁定style</p>
<button @click="changeClass()">修改class</button>
<button @click="changeStyle()">修改style</button>
</div>
</body>
<script src="js/vue.js"></script>
<script>
var vm = new Vue({
el:'#app',
data:{
isActive:false,
//默認style
currentStyle:{
width: '500px',
height: '200px',
backgroundColor: 'blue'
}
},
methods:{
changeClass(){
this.isActive = !this.isActive;
},
changeStyle(){
this.currentStyle = {
width: '300px',
height: '100px',
backgroundColor: 'orange',
color:'white',
fontSize:'30px'
}
}
}
})
</script>
</html>