[Vue.js]v-bind(片方向バインディング)
公開日:2026-02-18
更新日:2026-02-18
更新日:2026-02-18
1. 概要
v-bind(片方向バインディング)でコンポーネントに値を渡します。
動作確認:Vite 7.3.1、Vue.js 3.5.25
動作確認:Vite 7.3.1、Vue.js 3.5.25
2. サンプル
2.1 コード
src/App.vue
src/components/Message.vue
コード
<script setup lang="ts">
import { ref } from 'vue';
import Message from './components/Message.vue';
const count = ref(0);
</script>
<template>
<button @click="count++">Click</button><br /><br />
<!-- v-bind を使用して、コンポーネントの props に値を渡す -->
<Message v-bind:msg="count" sub-msg="Sub Message" /><br>
<!-- v-bind を省略した省略記法 -->
<Message :msg="count" :sub-msg="'Sub Message'" /><br>
<!-- 複数属性一括バインド -->
<Message :="{msg: count, subMsg: 'Sub Message'}" /><br>
<Message v-bind="{msg: count, subMsg: 'Sub Message'}" /><br>
</template>
src/components/Message.vue
コード
<script setup lang="ts">
defineProps<{ msg: string | number, subMsg?: string}>()
</script>
<template>
<h1>{{ msg }}</h1>
<p>{{ subMsg }}</p>
</template>2.2 動作内容
実行してボタンをクリックすると、Message コンポーネントで表示している数値がカウントアップします。
2.3 v-bind の書き方
コンポーネントに値を渡すには、
コロンから始まる書き方は、v-bind の省略記法です。
通常は省略記法を使用しますが、
v-bind を使用すると、属性を一括して指定する書き方ができます。
また、文字列リテラルを渡す場合に限っては、
この場合、数値も文字列として扱われます。
v-bind を使って文字列リテラルを渡す場合は、ダブルクォートの中が式として評価されるため、さらにシングルクォートで囲う必要があります。
コード
:属性名(or プロパティ名)="式"
v-bind:属性名(or プロパティ名)="式"
のように書きます。コロンから始まる書き方は、v-bind の省略記法です。
通常は省略記法を使用しますが、
v-bind を使用すると、属性を一括して指定する書き方ができます。
また、文字列リテラルを渡す場合に限っては、
コード
属性名="文字列"
のようにして、v-bind を使用しないことが多いです。この場合、数値も文字列として扱われます。
v-bind を使って文字列リテラルを渡す場合は、ダブルクォートの中が式として評価されるため、さらにシングルクォートで囲う必要があります。
コード
:属性名="'文字列'"2.4 props(プロパティ名)の命名規則
コンポーネント側で defineProps で props(プロパティ)を定義しますが、
この時の名前はキャメルケースにします。
但し、テンプレート側では、ケバブケースにします。
この時の名前はキャメルケースにします。
但し、テンプレート側では、ケバブケースにします。
3. 既存の属性にバインディング
既存の class や style などにもバインディングすることができます。
3.1 動的に style の変更
src/App.vue
既存の属性の前に「:」を付けてバインディングできます。
コード
<script setup lang="ts">
import { ref } from 'vue';
const color = ref("");
const setColor = (colorName: string) => {
color.value = colorName;
}
</script>
<template>
<h1 :style="{ color: color }">TEST</h1>
<button @click="setColor('red')">Red</button>
<button @click="setColor('blue')">Blue</button>
<button @click="setColor('green')">Green</button>
</template>
ボタンをクリックすると、即座に文字の色が変更されます。既存の属性の前に「:」を付けてバインディングできます。
3.2 動的に class, href, value の変更
src/App.vue
コード
<script setup lang="ts">
import { ref } from 'vue';
const cls = ref("");
const value = ref("");
const url = ref("");
const setAttr = () => {
cls.value = "text-red";
value.value = "100";
url.value = "https://9cubed.info/";
}
</script>
<template>
<h1 :class="cls">TEST</h1>
<input type="text" :value="value" /><br>
<a :href="url" target="_blank">{{ url }}</a><br>
<button @click="setAttr()">Click</button>
</template>
<style scoped>
.text-red {
color:red;
}
</style>
ボタンをクリックすると、即座に文字の色、入力欄の値、リンクの URL が変更されます。
