Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multi-layer deep v-model data-binding in vue3

Suppose I have two components, one being just a simple input:

<!-- Child.vue -->
<template>
    <input v-model="value" />
</template>

Now suppose I have a parent element, and I would like to v-model bind the child input's value.

Pseudo-code:

<!-- Form.vue -->
<template>
    <Child v-model:value="parentVariable"/>
</template>

So that way the value of the Child's input lives outside of the state of the Child component. (Or it is present in both and are binded together.)

The question is how do I two-way data-bind a variable in a parent component, to an input in the child's component?

(I am using vue3) (If there is a best practice for this, please inform me.)

like image 829
Péter Szabó-tóth Avatar asked Jul 12 '26 21:07

Péter Szabó-tóth


1 Answers

A solution is documented in the docs

you can use emit and props to propagate v-model to the parent component

Example from docs:

app.component('custom-input', {
  props: ['modelValue'],
  emits: ['update:modelValue'],
  template: `
    <input v-model="value">
  `,
  computed: {
    value: {
      get() {
        return this.modelValue
      },
      set(value) {
        this.$emit('update:modelValue', value)
      }
    }
  }
})
like image 51
Daniel Avatar answered Jul 15 '26 12:07

Daniel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!