vue v-bind 实现
v-bind 基础语法
v-bind 用于动态绑定 HTML 属性或组件 props 到 Vue 实例的数据。基础语法为 v-bind:attribute="expression" 或简写为 :attribute="expression"。
<!-- 绑定 HTML 属性 -->
<img v-bind:src="imageUrl" :alt="imageAlt">
<!-- 绑定组件 props -->
<child-component :message="parentMessage"></child-component>
动态绑定 class 和 style
通过对象或数组语法实现动态样式绑定。
对象语法:根据数据布尔值决定是否应用 class
<div :class="{ active: isActive, 'text-danger': hasError }"></div>
对应数据:
data() {
return {
isActive: true,
hasError: false
}
}
数组语法:直接绑定多个 class
<div :class="[activeClass, errorClass]"></div>
对应数据:
data() {
return {
activeClass: 'active',
errorClass: 'text-danger'
}
}
绑定内联样式
对象语法:CSS 属性名可用驼峰或短横线格式(需引号)
<div :style="{ color: textColor, 'font-size': fontSize + 'px' }"></div>
数组语法:组合多个样式对象
<div :style="[baseStyles, overridingStyles]"></div>
绑定 props 到组件
父组件通过 v-bind 向子组件传递动态 props:
<child-component :user-data="currentUser" :config="{ editable: true }"></child-component>
子组件通过 props 接收:
props: ['userData', 'config']
修饰符应用
.prop:强制绑定为 DOM property 而非 attribute<div :title.prop="dynamicTitle"></div>.camel:将短横线属性名转换为驼峰式(针对 DOM 模板)<svg :view-box.camel="viewBox"></svg>
注意事项
- 避免直接绑定复杂表达式,建议通过计算属性优化性能。
- 动态绑定
src或href时,确保路径是响应式数据。 - 组件 prop 绑定需遵循单向数据流原则,避免直接修改子组件接收的 props。







