たまにやりたくなる、カスタムコンポーネントのv-model対応。忘れないようにメモします。

公式ドキュメント: https://v3.ja.vuejs.org/guide/migration/v-model.html

Vue2

  • value Propsで受け取る
  • input イベントを発火する

<template>
  <div><input type="text" :value="value" @input="input" /></div>
</template>

<script>
export default {
  name: "MyInput",
  props: {
    value: {
      type: String,
      default: ""
    }
  },
  methods: {
    input(event){
      const val = event.target.value;
      this.$emit('input', val);
    }
  }
}
</script>

Vue3

  • modelValue Propsで受け取る
  • update:modelValue を発火する
<template>
  <div><input type="text" :value="modelValue" @input="input" /></div>
</template>

<script>
export default {
  name: "MyInput",
  props: {
    modelValue: {
      type: String,
      default: "",
    },
  },
  methods: {
    input(event) {
      const val = event.target.value;
      this.$emit("update:modelValue", val);
      console.log(val);
    },
  },
};
</script>