class样式或style样式的绑定,【vue】:class和:style介绍过,本篇主要作总结用。
绑定class样式
- 绑定的class样式是一个字符串。适用场景:类名不确定,需要动态指定。
- 绑定的class样式是一个数组。适用场景:类名个数不确定,类名也不确定。
- 绑定的class样式是一个对象。适用场景:类名个数确定,类名也确定,但用哪个需要动态指定。
看个具体的例子。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>demo1</title>
<script src="../js/vue.js"></script>
<style>
.basic{
width: 200px;
height: 100px;
border:1px solid #888;
}
.happy{
background: goldenrod;
}
.sad{
background: blue;
}
.normal{
background: #eee;
}
.test1{
border-radius: 10px;
}
.test2{
font-size: 36px;
}
.test3{
font-weight: bolder;
}
</style>
</head>
<body>
<div id="root">
<!--绑定class样式:字符串写法,适用于 类名不确定,需要动态指定 的场景-->
<div class="basic" :class="mode" @click="changeMode">test</div><br/><br/>
<!--绑定class样式:数组写法,适用于 类名个数不确定,类名也不确定 的场景-->
<div class="basic" :class="classArr">test</div><br/><br/>
<!--绑定class样式:对象写法,适用于 类名个数确定,类名也确定,但动态决定用不用 的场景-->
<div class="basic" :class="classObj">test</div><br/><br/>
</div>
<script>
new Vue({
el:"#root",
data:{
mode:"happy",
classArr:["test1","test2","test3"],
classObj:{
test1:true,
test2:true
},
},
methods:{
changeMode(){
const arr = ["happy","sad","normal"];
this.mode = arr[Math.floor(Math.random()*3)];
}
}
})
</script>
</body>
</html>
绑定style样式
- 绑定的style样式是一个对象。
- 绑定的style样式是一个数组。
看个具体的例子。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>demo1</title>
<script src="../js/vue.js"></script>
<style>
.basic{
width: 200px;
height: 100px;
border:1px solid #888;
}
</style>
</head>
<body>
<div id="root">
<!--绑定style样式:对象写法-->
<div class="basic" :style="styleObj">test</div><br/><br/>
<!--绑定style样式:数组写法-->
<div class="basic" :style="[styleObj1,styleObj2]">test</div><br/><br/>
<!--绑定style样式:数组写法-->
<div class="basic" :style="styleArr">test</div><br/><br/>
</div>
<script>
new Vue({
el:"#root",
data:{
styleObj:{
fontSize:'40px'
},
styleObj1:{
fontSize:"40px"
},
styleObj2:{
color:"orange"
},
styleArr:[
{
fontSize:"40px"
},
{
color:"red"
},
{
backgroundColor:"orange"
}
]
}
})
</script>
</body>
</html>
当样式属性值是一个变量时,应该怎么写?
<body>
<div id="root">
<h2 :style="styleObj">欢迎来到深圳!</h2>
</div>
<script>
Vue.config.productionTip = false;
new Vue({
el:"#root",
data:{
opacity:1,
styleObj:{
opacity:opacity
}
}
})
</script>
</body>
以上写法显然不对。正确的应该是,
<body>
<div id="root">
<h2 :style="{opacity:opacity}">欢迎来到深圳!</h2>
</div>
<script>
Vue.config.productionTip = false;
new Vue({
el:"#root",
data:{
opacity:1
}
})
</script>
</body>