Vue v-bind 指令
示例
使用 v-bind
指令更改 <div>
元素的背景颜色。
<template>
<h2>Example v-bind Directive</h2>
<p>The v-bind directive connects the style attribute of the DIV element to the 'colorVal' data property.</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 元素将自动更新为新的属性值。
“v-bind:
”的简写形式是“:
”,或者当与 .prop
修饰符一起使用时是“.
”。
这些修饰符可以与 v-bind
指令一起使用,但通常不需要
修饰符 | 详情 |
---|---|
.camel |
将属性名称从 kebab-case 转换为 camelCase。使用构建步骤或字符串模板时不需要此选项。 |
.prop |
强制将绑定设置为 DOM 属性。除非处理自定义元素,否则 Vue 会找出 v-bind 提供的键是 DOM 属性还是元素的属性,并相应地进行绑定。 |
.attr |
强制将绑定设置为 DOM 属性。除非处理自定义元素,否则 Vue 会找出 v-bind 提供的键是 DOM 属性还是元素的属性,并相应地进行绑定。 |
更多示例
示例 1
使用 v-bind
发送 'img' prop,数据类型为布尔值(true/false)。
<template>
<h2>Example v-bind Directive</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>Example v-bind Directive</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>Using the '.prop' shorthand so that 'v-bind:indeterminate.prop' becomes '.indeterminate':</p>
<button v-on:click="indetVal = !indetVal">Toggle</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>
运行示例 »
相关页面
Vue 教程:Vue CSS 绑定
Vue 教程:Vue v-bind 指令
Vue 教程:Vue Props