Search code examples
vue.jsvuejs3

Getting a computed object in the parent from a child component?


I have an object in a child component, something like:

const obj = computed(() => ({
  abc: someField.value,
  xyz: anotherField.value,
}));

In the parent I want to get this object, how can I do this?


Solution

  • Using watch:

    In the child component:

    const emit = defineEmits(['obj-changed']);
    
    watch(
      () => obj.value,
      (val) => emit('obj-changed', val),
      { immediate: true }
    );
    

    In the parent component:

    <child-component @obj-changed="handleObjChanged" />
    
    const handleObjChanged = (val) => console.log(val);
    

    Using defineExpose:

    In the child componenet:

    defineExpose({ obj });
    

    In the parent component:

    <child-component ref="child" />
    
    const child = ref();
    

    And finally access it using:

    child.value?.obj