v-bind
缩写::
预期:any (with argument) | Object (without argument)
参数:attrOrProp (optional)
修饰符:
- .prop - 被用于绑定 DOM 属性 (property)。(差别在哪里?) .camel - (2.1.0+) 将
- kebab-case 特性名转换为 camelCase. (从 2.1.0 开始支持) .sync (2.3.0+)
- 语法糖,会扩展成一个更新父组件绑定值的 v-on 侦听器。
用法:
动态地绑定一个或多个特性,或一个组件 prop 到表达式。
在绑定 class 或 style 特性时,支持其它类型的值,如数组或对象。可以通过下面的教程链接查看详情。
在绑定 prop 时,prop 必须在子组件中声明。可以用修饰符指定不同的绑定类型。
没有参数时,可以绑定到一个包含键值对的对象。注意此时 class 和 style 绑定不支持数组和对象。
列子
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <script src="https://cdn.jsdelivr.net/npm/[email protected]"></script></head><style> .red{ background-color: red; } .width{ width:400px; }</style><body> <!-- Vue指令 --> <!-- 1.v-bind 绑定属性 --> <!-- v-bind <==> : --> <div id="app"> <h4 :class="[{red : true},h5Class]">{{ name }}</h4> <img v-bind:src="imgUrl" v-bind:alt="name" :style="[{width:imgWidth},imgStyle]"/> </div>
<script> // v-bind 绑定属性 const vm=new Vue({ el: '#app', data:{ name:"VUE", imgUrl:"https://cn.vuejs.org/images/logo.png", h4Class:'red', h5Class:'width', imgWidth: '200px', imgStyle: { border: '10px solid red' }
}
}) </script>
</body></html>
运行结果
点击变化颜色的小实例
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <script src="https://cdn.jsdelivr.net/npm/[email protected]"></script></head><style> .red{ background-color: red; } .green{ background-color: green; } .yellow{ background-color: yellow; }
</style><body> <!-- Vue指令 --> <!-- 1.v-bind 绑定属性 --> <!-- v-bind <==> : --> <!-- 2.v-on:xxx --> <div id="app"> <button v-on:click="handleClick">点击</button> <h4 :class="h4ClassArr[h4Index]">{{ name }}</h4> </div>
<script> // v-bind 绑定属性 const vm=new Vue({ el: '#app', data:{ name:"VUE", imgUrl:"https://cn.vuejs.org/images/logo.png", h4Class:'red', h5Class:'width', imgWidth: '200px', imgStyle: { border: '10px solid red' }, h4ClassArr:['red','green','yellow'], h4Index:0, h4Count:0 }, methods:{ handleClick(){ this.h4Index= ++ this.h4Count % 3
}
}
}) </script>
</body></html>
运行结果