do you need to emit event for reactive objects in vue3?

Viewed 1552

i've not really understood how v-model works for components, check my code:

    <template>
      <a-form-item name="bananas" label="bananas">
        <a-input v-model:value="test.bananas" />
      </a-form-item>
    </template>
    
    <script>
    import { computed, defineComponent } from 'vue'
    
    export default defineComponent({    
      props: {
        formData: {
          type: Object,
          required: true
        }
      },
      setup(props) {
        const test = computed(() => props.formData)
        return { test }
      }
    })
    </script>

where formData in parent component is a reactive object

    <InnerComponent v-model:formData="formData" />

    const formData = reactive({
      name:'',
      .....
      bananas: 'bananas',
    })

this code "works", or rather it seems that the formData object is updated when the input "bananas" is changed .... but how? reading the documents using v-model in the components i should also define an update function for it, also this is an object and there are no examples using responsive objects

Can someone explain?

all this because having to create a very large form, I need to divide the various sections into sub-components, passing the reactive object to all the children

1 Answers

from https://stackoverflow.com/a/65604790/197546

v-model is syntactical sugar for :value and @change
Instead of <input v-model="name">, you could use
<input :value="name" @update:model-value="v => name=v">

If you are using v-model, you don't need to use emits and listeners. In vue 3 you can specify which variable you'd like to apply this syntactic sugar to via the colon definition, as you have done with v-model:formData. This allows components to have more than one variables be available through v-model which can be very helpful in more advanced component setups.

if you're passing a reactive variable you don't need to use v-model at all, since reactive exposes Vue's internals so in the case of reactive the reactivity is handled separate of the parent-child interaction. Whether the reactive is passed to the child as a prop or from a global reference, the reactivity will work across all instances.

On a side note, refs will not allow this in the same way. while you can still pass them as global, passing it as a prop will not work. It will behave like a regular prop, in the it will continue to receive updates from the parent, but local changes do not propagate outside of the component scope.

Related