Home > Mobile >  Why does @change or @input work with custom v-model component?
Why does @change or @input work with custom v-model component?

Time:10-05

Let's say I've created a custom component Comp.vue that basically is an wrapped input element with a model-value prop and @update="$emit('update:modelValue', $event.target.value).

It might look like this:

<template>
  <div>
  <label :for="name" class="block relative">
    <div>
        {{ label }}
    </div>
        <input
          :name="name"
          :type="type"
          :value="modelValue"
          @input="$emit('update:modelValue', $event.target.value)"
        />
  </label>
    </div>
</template>

<script>

export default {
  props: {
    label: {
      required: true,
      type: String,
    },
    modelValue: {
      required: false,
      default: "",
      type: [String, Number],
    },
    type: {
      default: "text",
      type: String,
    },
    name: {
      required: false,
      type: String,
      default: "",
    },
  },
  emits: ["update:modelValue"],
};
</script>

Now I've imported that component in App.vue.

Why does this work:

<Comp @change="doSth1()" />
<Comp @input="doSth2()" />

My custom Comp.vue never emits any of those events.

I've created a custom playground that logs those events: enter image description here

CodePudding user response:

Because you're basicly passing modelValue as a prop. And I believe that when the value of modelValue changes it triggers an input or change event.

  • Related