Home > Blockchain >  multi-layer deep v-model data-binding in vue3
multi-layer deep v-model data-binding in vue3

Time:09-17

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.)

CodePudding user response:

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)
      }
    }
  }
})
  • Related