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