Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correct set v-model with computed method in Vue 3 Composition API?

I got an component:

<template>
  <input type="text" v-model="customerComponentModel" />
</template>
<script>
import { computed } from 'vue';
export default {
  props: {
    modelValue: Object,
  },
  setup(props, { emit }) {
    const customerComponentModel = computed({
      get: () => {
      if (props.modelValue) {
          return props.modelValue.Customer
        } else {
          return ''
        }
      },
      set: (value) => {
           ????
    });

    return { customerComponentModel };
  },
};
</script>

This component works fine if i send to it data thru modelValue. How can i set customerComponentModel value if props.modelValue not set in parent? I want use component in both way - with props and without. Thanks for help.

like image 990
Doom Avatar asked Jan 31 '26 20:01

Doom


1 Answers

Emit an update:modelValue event with the new object value. To update only the Customer field, the emitted value should be a clone of props.modelValue along with a new Customer field equal to the new value:

export default {
  props: {
    modelValue: Object,
  },
  setup(prop, { emit }) {
    const customerComponentModel = computed({
      //...
      set: (value) => {
        emit('update:modelValue', {
          ...props.modelValue,
          Customer: value,
        })
      }
    });

    return {
      customerComponentModel
    }
  }
}

demo

like image 103
tony19 Avatar answered Feb 03 '26 10:02

tony19