Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Vue 3 – Composition API – How to get props original value

I have a component that receive some props and emit a custom event. I need the emit to pass the value of the props as a parameter. No matter what I do I always receive a Proxy and not the original value. Here a simplification of my implementation:

    //child-component
    <script setup lang="ts">
        import { ref, unref } from "vue";

        const props = defineProps<{
             category: { id: number, label: string};
        }>();

        const emit = defineEmits(["sendcategory"]);
        const category = ref(props.category);
        const cat = unref(category);

        function send() {
            emit("sendcategory", cat);
       
    }
    <template>
       <div  @click="send" >
            {{ category.value.label }}
       </div>
    </template>

and here an example of parent component

    //parent-component
    <script setup lang="ts">

        import { ref } from "vue";
        import ChildComponent from "./ChildComponent.vue";

        const item = { id: 1, label: "testlabel" }

        function getcategory(category: {id: number, label: string}) {
            console.log(category);
        }
    </script>
    <template>
        <ChildComponent :category="item" @sendcategory="getcategory" />      
    </template>

I alwais get a Proxy object, i would like to receive from the child element an object (not reactive) equal to the one I passed as prop: { id: 1, label: "testlabel" }

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

To get original object of a proxy you can use toRaw()

However your code "smells"

const category = ref(props.category); creates a ref with the value of props.category at the time setup is executed (if props.category changes, value of category won’t).

Either use const { category } = toRefs(props); or skip this ref shenanigans altogether and just emit emit("sendcategory", toRaw(props.category));

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading