页面的样式可能会经常改变,这是采用class绑定和style绑定可以满足这些需求
class绑定
class绑定可以绑定字符串、对象、数组三种绑定方法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>04_class与style绑定</title>
<style>
.classA {
color: red;
}
.classB {
background: blue;
}
.classC {
font-size: 20px;
}
</style>
</head>
<body>
<div id="demo">
<h2>class绑定</h2>
<p :class="myClass">xxx是字符串</p>
<p :class="{classA: hasClassA, classB: hasClassB}">xxx是对象</p>
<p :class="['classA', 'classB']">xxx是数组</p>
</div>
<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript">
new Vue({
el: '#demo',
data: {
myClass: 'classA',
hasClassA: true,
hasClassB: false,
activeColor: 'red',
fontSize: '20px'
}
})
</script>
</body>
</html>
style绑定
style绑定一个对象,可以在对象中设置以键值对的格式设置多个属性值
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>04_class与style绑定</title>
<style>
.classA {
color: red;
}
.classB {
background: blue;
}
.classC {
font-size: 20px;
}
</style>
</head>
<body>
<div id="demo">
<h1>style绑定</h1>
<p :style="{color:activeColor, fontSize}">:style="{ color: activeColor, fontSize: fontSize + 'px' }"</p>
</div>
<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript">
new Vue({
el: '#demo',
data: {
myClass: 'classA',
hasClassA: true,
hasClassB: false,
activeColor: 'red',
fontSize: '20px'
}
})
</script>
</body>
</html>