Home > Back-end >  Vue3 - API Composition : Custom v-model prop
Vue3 - API Composition : Custom v-model prop

Time:01-24

In Vue2, the v-model bind to the prop value, but it's possible to define a other prop :

Vue.component('base-checkbox', {
  model: {
    prop: 'checked',
    event: 'change'
  },
  props: {
    checked: Boolean
  },
  template: `
    <input
      type="checkbox"
      v-bind:checked="checked"
      v-on:change="$emit('change', $event.target.checked)"
    >
  `
})

I want do the same in Vue 3 with API Composition.

How do you define a custom prop to v-model in Vue 3 with the API Composition?

Example :

<script setup lang="ts">

defineProps({
    msg: {
        type: String,
    }
});

defineEmits(['update:msg'])

defineModel('msg', 'update:msg'); 

</script>

<template>
    <div>
        {{ msg }}
    </div>
    <button @click="$emit('update:msg', 'Clicked!')">Switch</button>
</template>

Of course defineModel don't exist, but I must not be far from the truth.

CodePudding user response:

In Vue 3 the model option are removed and replaced with an argument on v-model

So if you want to change the v-model prop you can by changing the defineProps and defineEmits to use another name than modelValue.

However you cannot implicitly use v-model without adding the new custom prop name after the v-model.

You have to specify it like this : v-model:myCustomPropName.

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

<script setup>
import { defineProps, defineEmits } from "vue";

defineProps(["myCustomPropName"]);
defineEmits(["update:myCustomPropName"]);
</script>

Usage:

<MyCustomInput v-model:myCustomPropName="msg" />

Vue 3 props Doc : https://vuejs.org/guide/components/v-model.html

See the changes from Vue 2 to Vue 3 : https://v3-migration.vuejs.org/breaking-changes/v-model.html

  • Related