Vue 3 - 组合 API - 如何获取道具原始值

Pla*_*tic 2 vue.js vue-reactivity vue-props vue-composition-api

我有一个接收一些道具并发出自定义事件的组件。我需要发出来将 props 的值作为参数传递。无论我做什么,我总是收到一个代理而不是原始值。这是我的实现的简化:

    //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>
Run Code Online (Sandbox Code Playgroud)

这是父组件的示例

    //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>
Run Code Online (Sandbox Code Playgroud)

我总是得到一个 Proxy 对象,我想从子元素接收一个与我作为 prop 传递的对象相同的对象(非反应式):{ id: 1, label: "testlabel" }

Mic*_*evý 5

要获取代理的原始对象,您可以使用toRaw()

然而你的代码“有味道”

const category = ref(props.category);使用执行时ref的值创建一个(如果更改,则值不会)。props.categorysetupprops.categorycategory

要么使用const { category } = toRefs(props);或完全跳过这个参考恶作剧,然后发出emit("sendcategory", toRaw(props.category));