DEV Community

Cover image for How is vue attaching v-model to child component?
Simba
Simba

Posted on

How is vue attaching v-model to child component?

I'm currently using vuetify 3 in my project, I separated the vuetify v-text-field into a different component (Input.vue).

Image description

The code functions completely well, but I'm confused on how the v-model is being connected to the v-text-field in Input.vue. I'm passing the v-model as prop in Input component but I'm not connecting the v-model to the text-field in any way.
Image description

Image description

Is this behavior of vuetify library or vue itself? I normally pass my ref states to child component using provide/injects, but here I can't figure out how its possible.

Top comments (1)

Collapse
 
tqbit profile image
tq-bit • Edited

I could not find the source for this statement, but I believe it's a functionality of Vue itself.

v-model is a combination of v-bind and v-on. When a component template has only a single root element, it will automatically bind the attributes from the parent component that imports and uses it.

In your case, this means: v-text-field inherits all attributes you use in the parent component for Input.

If you have more than one element in your child component, you can change this behavior by using v-bind="$attrs" on the element to inherit the bindings.

Here is a full example in Vue 3 from my notes, if you're curious to fiddle with it :)

<template>
  <label>{{ label }}</label>
  <input
    v-bind="$attrs"
    :placeholder="label"
    class="field"
    :value="modelValue"
    @input="$emit('update:modelValue', $event.target.value)"
  />
</template>

<script>
export default {
  props: {
    label: {
      type: String,
      default: "",
    },

    modelValue: {
      type: [String, Number],
      default: "",
    },
  },
};
</script>
Enter fullscreen mode Exit fullscreen mode