gpt4 book ai didi

vue.js - Vue 3 - 组合 API - 如何获取 Prop 原始值

转载 作者:行者123 更新时间:2023-12-02 18:15:52 24 4
gpt4 key购买 nike

我有一个组件可以接收一些 Prop 并发出自定义事件。我需要发出来将 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>

这里是父组件的示例

    //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>

我总是得到一个 Proxy 对象,我想从子元素接收一个对象(非响应式(Reactive)),该对象等于我作为 prop 传递的对象:{ id: 1, label: "teSTLabel"}

最佳答案

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

但是你的代码“有味道”

const category = ref(props.category);创建 ref值为props.category当时setup被执行(如果props.category改变,category的值不会)。

使用const { category } = toRefs(props);或者完全跳过这个引用恶作剧,直接发出 emit("sendcategory", toRaw(props.category));

关于vue.js - Vue 3 - 组合 API - 如何获取 Prop 原始值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71599533/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com