前言
清明一共休息了四天,有三天没有学习,今天继续学习.
v-bind:class
首先准备如下的CSS代码:
span{
background: red;
display: inline-block;
padding: 10px;
color: #fff;
marin: 10px 0px;
}
.changeColor span{
background: greenyellow;
}
.changeLength span:after{
content: 'length';
margin-left: 10px;
}
如果需要动态绑定CSS,用法如下:
<div v-on:click="changeColor = !changeColor"
v-bind:class="{changeColor:changeColor}">
<span>allen</span>
这里v-bind:class="{changeColor:changeColor}"
中{}
内第一个changeColor
表示需要绑定的CSS
样式,第二个changeColor
表示是否采用这个样式.同时对这个div
添加了一个点击事件,用来更改changeColor
的值.
另外,还有一种方法也可以实现动态绑定:
<button @click="changeLength = !changeLength">changeLength</button>
<div v-bind:class="compare">
<span>marry</span>
</div>
这里是绑定了一个compare
的方法,方法实现如下:
<script>
var app = new Vue({
el:'#app',
data:{
changeColor:false,
changeLength:false
},
computed:{
compare:function () {
return {
changeColor:this.changeColor,
changeLength:this.changeLength
}
}
}
});
</script>
完整代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>The forth day</title>
<script src="../1/vue.js"></script>
<link rel="stylesheet" href="../2/2.css">
</head>
<body>
<div id="app">
<h1>动态绑定css</h1>
<h2>动态改变颜色</h2>
<div v-on:click="changeColor = !changeColor" v-bind:class="{changeColor:changeColor}">
<span>allen</span>
</div>
<h2>动态改变长度</h2>
<button @click="changeLength = !changeLength">changeLength</button>
<div v-bind:class="compare">
<span>marry</span>
</div>
</div>
<script>
var app = new Vue({
el:'#app',
data:{
changeColor:false,
changeLength:false
},
computed:{
compare:function () {
return {
changeColor:this.changeColor,
changeLength:this.changeLength
}
}
}
});
</script>
</body>
</html>
网友评论