【Vue3】v-modelとは?使い方を紹介する

v-modelとは?

v-modelは、フォームの入力要素(inputなど)に入力された値を同期的に使用するために使います。

Vue3対応です。

v-modelが使える要素は、

  • input
  • select
  • textarea
  • オリジナルコンポーネント

があります。

この記事を書いた人

@takasqr アプリケーション開発が大好きなエンジニア。Vue、Swift、Electrom などでアプリを作って公開している。AWS や Firebase などのクラウドサービスも好き。

作ったアプリKeyScript

使い方

基本形

基本的な使い方です。

<script>
  import { ref } from 'vue'
  export default {
    setup() {
      let inputData = ref('')
      return {
        inputData
      }
    }
  }
</script>

<template>
  <input v-model="inputData" />
  <p>inputData : {{ inputData }}</p>
</template>

v-modelはシンタックスシュガー

下のコードは同じ動きをします。

<input
 v-on:input="inputData = $event.target.value"
 v-bind:value="inputData"
/>
<input v-model="inputData" />

自作のコンポーネントで使う

親コンポーネント。

<script>
  import { ref } from 'vue'
  import VModelChildren from './VModelChildren.vue'

  export default {
    components: { VModelChildren },
    setup() {
      let inputData = ref('')
      return {
        inputData
      }
    }
  }
</script>

<template>
  <VModelChildren v-model="inputData" />
  <p>inputData : {{ inputData }}</p>
</template>

子コンポーネント。

<script>
  export default {
    props: ['modelValue'],
    emits: ['update:modelValue']
  }
</script>

<template>
  <input
    :value="modelValue"
    @input="$emit('update:modelValue', $event.target.value)"
  />
</template>

複数の値をv-modelでバインディングする

カスタムコンポーネントを使ってる時などに、複数の値をv-modelで使いたくなるかもしれません。

Vue3から一つの要素に複数の値をv-modelできるようになりました。

<script>
  import { ref } from 'vue'
  import VModelChildren from './VModelChildren.vue'

  export default {
    components: { VModelChildren },
    setup() {
      let height = ref('')
      let weight = ref('')
      return {
        height,
        weight
      }
    }
  }
</script>

<template>
  <VModelChildren v-model:height="height" v-model:weight="weight" />
  <p>height : {{ height }}</p>
  <p>weight : {{ weight }}</p>
</template>
<script>
  export default {
    props: {
      height: String,
      weight: String
    },
    emits: ['update:height', 'update:weight']
  }
</script>

<template>
  <input
    :value="height"
    @input="$emit('update:height', $event.target.value)"
  />
  <input
    :value="weight"
    @input="$emit('update:weight', $event.target.value)"
  />
</template>