1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

v-modelの使い方と双方向データバインディング

Posted at

フォーム入力バインディング

フォーム(input要素, select要素, textarea要素など)の入力値 / 選択値をvueインスタンスdataを同期させる 「双方向データバインディング」を行うにはv-modelディレクティブを使用する。

index.html
<div id="app">
  <input v-model="message">
  <p>{{ message }}</p>
</div>
vue.js

new Vue ({
  el: '#app',
  data: {
    message: ''
  }
})

v-modelディレクティブは次の2つの処理を一つにまとめています。
(1) データバインディングで、要素のvalue属性(値)を更新する

v-bind:value="message"

(2) イベントハンドリング(イベントが発生したときに呼び出される処理)で、受け取った値をデータに代入

入力フォームにユーザが入力

↓  inputイベントが発生

this.message = event.target.value

で値を得られる。
messageプロパティの値が変更されます。

DOM要素へのデータバインディングと、要素から取得したデータをリアクティブデータに反映させるこの2つの処理を自動化した構文が**v-model**

ラジオボタン

ラジオボタンのデフォルトの値の方は文字列

index.html

<div>
    <span>性別:</span>
    <label>
      男性
      <input type="radio" value="male" v-model="form.sex">
    </label>
    <label>
      女性
      <input type="radio" value="female" v-model="form.sex">
    </label>
    <p>性別: {{ getRadioValue }}</p>
  </div>
vue.js

data: {
  return {
    //省略
    form: {
      sex: '',

    },
  }
},

value属性の値がバインディングされるので female / male のどちらかが
dataの中のsexプロパティへ代入されます。

セレクトボックス

index.html
<div>
  <select v-model="form.selected">
    <option disabled value="">--選択してください--</option>
    <option>A</option>
    <option>B</option>
    <option>C</option>
    <option>D</option>
  </select>
</div>

単数選択

vue.js
data: {
  return {
    //省略
    form: {
      selected: ''
    },
  }
},

複数選択

vue.js
data: {
  return {
    //省略
    form: {
      selected: []
    },
  }
},

チェックボックス

チェックボックスのデフォルト値の値の型はBoolean

index.html

<div>
  <label>
    <input type="checkbox" v-model="form.checked">
    20際以上です
  </label>
</div>
vue.js
data: {
  return {
    //省略
    form: {
      checked: true
    },
  }
},
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?