Home > Enterprise >  Vue 3 - Composition API - How to get props original value
Vue 3 - Composition API - How to get props original value

Time:03-24

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" }

CodePudding user response:

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

  • Related