Vue v-bind 指令
实例
使用 v-bind
指令更改 <div>
元素的背景颜色。
<template>
<h2>v-bind 指令</h2>
<p>v-bind 指令将 DIV 元素的样式属性连接到 colorVal 数据属性。</p>
<div v-bind:style="{ backgroundColor: colorVal }">DIV element</div>
<p>Use the input type="color" box below to change the color.</p>
<p><input type="color" v-model="colorVal"> <pre>colorVal: '{{ colorVal }}'</pre></p>
</template>
定义与用法
v-bind
指令用于将 HTML 属性绑定到 Vue 实例中的属性(上面的实例),或传递 props(下面的实例 1)。
如果我们更改 Vue 实例属性,并且该属性通过 v-bind
绑定到 HTML 属性,则由于 Vue 的反应系统,HTML 元素将自动更新为新的属性值。
当与 .prop
修饰符一起使用时,v-bind:
的简写为 :
或 .
。这些修饰符可以与 v-bind
指令一起使用,但通常不需要:
修饰符 | 详情 |
---|---|
.camel | 将属性名称从 kebab-case 转换为 camelCase 当使用构建步骤或使用字符串模板时,不需要这样做 |
.prop | 强制将绑定设置为 DOM 属性除非使用自定义元素,否则 Vue 会发现 v-bind 提供的键是 DOM 属性还是元素的属性,并适当地绑定该键。 |
.attr | 强制将绑定设置为 DOM 属性除非使用自定义元素,否则 Vue 会发现 v-bind 提供的键是 DOM 属性还是元素的属性,并适当地绑定该 key。 |
更多实例
实例 1
使用 v-bind
发送 'img' prop,数据类型为布尔(true/false)
<template>
<h2>v-bind 指令实例</h2>
<p>Two props are sent to the component. We must use v-bind for the prop with 'boolean' data type.</p>
<button v-on:click="this.img = !this.img">Toggle 'img' prop value</button> {{ img }}
<info-box
turtle-text="Turtles can hold their breath for a long time."
v-bind:turtle-img="img"
/>
</template>
<script>
export default {
data() {
return {
img: true
}
}
}
</script>
实例 2
使用 v-bind:
简写 :
。
<template>
<h2>v-bind 指令实例</h2>
<p>Two props are sent to the component. We must use v-bind for the prop with 'boolean' data type.</p>
<button v-on:click="this.img = !this.img">Toggle 'img' prop value</button> {{ img }}
<info-box
turtle-text="Turtles can hold their breath for a long time."
:turtle-img="img"
/>
</template>
<script>
export default {
data() {
return {
img: true
}
}
}
</script>
实例 3
使用 .prop
修饰符更改复选框的 indeterminate
DOM 属性。
<template>
<p>Using the '.prop' modifier to toggle the 'indeterminate' appearance of the checkbox:</p>
<button v-on:click="indetVal = !indetVal">Toggle</button>
<p>
<input type="checkbox" v-bind:indeterminate.prop="indetVal"> Checkbox
</p>
</template>
<script>
export default {
data() {
return {
indetVal: false
};
}
};
</script>
<style>
input {
margin: 20px;
scale: 2;
}
</style>
实例 4
使用 .prop
修饰符简写和 v-bind
简写,因此 v-bind:indeterminate.prop
变成 .indeterminate
。
<template>
<p>使用 the '.prop' 简写因此 'v-bind:indeterminate.prop' 变成 '.indeterminate':</p>
<button v-on:click="indetVal = !indetVal">切换</button>
<p>
<input type="checkbox" .indeterminate="indetVal"> Checkbox
</p>
</template>
<script>
export default {
data() {
return {
indetVal: false
};
}
};
</script>
<style scoped>
input {
margin: 10px;
scale: 2;
}
</style>