绑定样式
1. 绑定行内样式
- 绑定对象语法:v-bindstyle="{backgroundColor:pink,width:width}".
- 绑定数据语法:v-bind:style="{myDiv,xxx}".
数组中是一个一个的样式对象,例如:myDiv:{backgroundColor:‘red’,width:‘100px’} 如果只绑定一个对象,那么中括号可以省略. - 上述语法中:pink,width,myDiv均为data数据.
- 绑定之后可以通过操作data数据来改变样式,绑定样式才能操作样式.
<!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>Document</title>
<script src="./js/vue.js"></script>
</head>
<body>
<div id="app">
<!--绑定样式属性值-->
<div v-bind:style="{backgroundColor:pink,width:width,height:height}">
<!--绑定样式对象:可以添加多个样式对象,放到数组中-->
<div v-bind:style="[myDiv,myDiv]"></div>
</div>
</div>
<script>
var vm = new Vue({
el:'#app',
data:{
pink:'pink',
width:'100%',
height:'200px',
myDiv:{
backgroundColor:'red',
width:'100px',
height:'100px'
}
}
});
</script>
</body>
</html>
2. 绑定类样式
- 绑定对象语法:v-bind:class="{box}"
data中需要有一个属性:box:‘box’,值box是样式的类名 - 绑定数组语法:v-bind:class="{box1,box2}"
<!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>Document</title>
<script src="./js/vue.js"></script>
<style>
.box {
background-color: pink;
width: 100%;
height: 200px;
}
.inner {
background-color:red;
width: 100px;
height: 50px;
border: 2px solid white;
}
</style>
</head>
<body>
<div id="app">
<div v-bind:class='box'>
<div v-bind:class='inner'></div>
<div v-bind:class='{inner,inner2}'></div>
</div>
</div>
<script>
var vm = new Vue({
el:'#app',
data:{
box:'box', //这里的属性值box就是类名,不需要添加点
inner:'inner'
}
});
</script>
</body>
</html>
|