在Vue中v-bind用于绑定一个或多个属性值,或者向另一个组件传递Props值。
1.v-bind介绍
作用: 动态绑定属性
语法:
v-bind: 属性名 = "数据名"
缩写(也叫语法糖):
: 属性名 = "数据名"
2.v-bind动态绑定class(对象方法)
语法:
v-bind: class = { 类名1: 布尔值, 类名n......}
例:
<!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>
<style>
.active{
color: red;
}
</style>
</head>
<body>
<div class="app">
<h1 :class="{active: isActive, line: isLine}">{{message}}</h1>
</div>
//所引用的Vue文件
<script src="../vue.js"></script>
<script>
const app = new Vue({
el: '.app',
data: {
message: '你好Vue!',
isActive: true,
isLine: true
},
})
</script>
</body>
</html>
图例:
3.v-bind动态绑定class(数组语法)
语法:
v-bind: class = [ 数组名1, 数组名n......]
例:
<div id="app">
<h1 :class="[active, lineL]">{{message}}</h1>
</div>
<script src="../vue.js"></script>
<script>
const app = new Vue({
el:'#app',
data: {
message: '你好Vue!',
active: 'a',
lineL: 'b'
},
})
</script>
例图:
4.v-bind动态绑定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>Document</title>
<style>
.active{
color: red;
}
</style>
</head>
<body>
<div id="app">
<h1 :style="{fontSize: finalSize + 'px', background: finalColor}">{{message}}</h1>
</div>
<script src="../vue.js"></script>
<script>
const app = new Vue({
el:'#app',
data: {
message: '你好Vue!',
finalSize: 100,
finalColor: 'red',
},
})
</script>
</body>
</html>
例图:
5.v-bind动态绑定style(数组语法)
: style = [ 数组名1, 数组名2 ....]
例:
<div id="app">
<h1 :style="[style1, style2]">{{message}}</h1>
<!-- <h1 :style="getStyles()">{{message}}</h1> -->
</div>
<script src="../vue.js"></script>
<script>
const app = new Vue({
el:'#app',
data: {
message: '你好Vue!',
finalSize: 100,
finalColor: 'red',
style1: {background: 'red'},
style2: {color: 'white'}
},
})
</script>
例图: