在Vue中,样式的绑定可以通过两种方式,第一种是通过class,第二种是通过style
一、class
1. class的对象绑定
:class="{activated: isActivated}"
在这种形式下,当isActivated
为true时,则class="activated"
,当isActivated
为
false时,则class无值。因此,可以通过对class进行样式设置从而达到控制样式的目
的
<!DOCTYPE html>
<html>
<head>
<title>vue</title>
<script src="./vue.js"></script>
<style>
.activated {
color: red;
}
</style>
</head>
<body>
<div id="root">
<div @click="handleClick"
:class="{activated: isActivated}"
>
Hello World
</div>
</div>
<script>
var vm = new Vue({
el: '#root',
data: {
isActivated: false
},
methods: {
handleClick: function () {
this.isActivated = !this.isActivated
}
}
});
</script>
</body>
</html>
2.:class="[activated]"
在这种模式下class的值为,表达式activated
属性的值,在数组中可以放入多个
属性
<!DOCTYPE html>
<html>
<head>
<title>vue</title>
<script src="./vue.js"></script>
<style>
.activated {
color: red;
}
</style>
</head>
<body>
<div id="root">
<div @click="handleClick"
:class="[activated]"
>
Hello World
</div>
</div>
<script>
var vm = new Vue({
el: '#root',
data: {
activated: ""
},
methods: {
handleClick: function () {
this.activated = this.activated == ""
? "activated" : "";
}
}
});
</script>
</body>
</html>
二、style
:style="[styleObj]"
在这种模式下,数组中存放的是表达样式的对象,可以放入多个样式对象
<!DOCTYPE html>
<html>
<head>
<title>vue</title>
<script src="./vue.js"></script>
</head>
<body>
<div id="root">
<div @click="handleClick"
:style="[styleObj, {fontSize: '20px'}]"
>
Hello World
</div>
</div>
<script>
var vm = new Vue({
el: '#root',
data: {
styleObj: {
color: "black"
}
},
methods: {
handleClick: function () {
this.styleObj.color = this.styleObj.color == "red"
? "black" : "red";
}
}
});
</script>
</body>
</html>