无法在子组件中获取对象值,如果该属性是响应式的。

huangapple go评论66阅读模式
英文:

Can't get object values in child component prop if prop is reactive

问题

I have a Parent component and try to pass reactive object as props:

<template>
    <Child :info="reactiveObject" />
</template>
<script setup>
const reactiveObject = reactive({ name: "Object", id: "443" })
</script>

Child.vue:

<template>
    <div> {{ info.name }} </div>
</template>
<script setup>
const props = defineProps({
    info: Object
})
</script>

and i get Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'name')

if i pass full props object info into double brackets i get values in html like image

Why i cant get name through info.name?

英文:

I have a Parent component and try to pass reactive object as props:

&lt;template&gt;
    &lt;Child :info=&quot;reactiveObject&quot; /&gt;
&lt;/template&gt;
&lt;script setup&gt;

const reactiveObject = reactive({ name: &quot;Object&quot;, id: &quot;443&quot;})

Child.vue

&lt;template&gt;
    &lt;div&gt; {{ info.name }} 
&lt;/template&gt;
&lt;script setup&gt;
const props = defineProps({
    info: Object,})

and i get Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'name')

if i pass full props object info into double brackets i get values in html like
image

Why i cant get name throught info.name?

答案1

得分: 1

你在使用reactive时应该从Vue中导入它。这是Vue 3的特性。当你需要在Vue中使用某些东西时,你必须先导入它。

import { reactive } from 'vue'
const reactiveObject = reactive({ name: "Object", id: "443" })

当你忘记从Vue中导入时,你不能在模板中使用它。这是不正确的语法。

你应该阅读更多关于Vue的文档,这是链接

英文:

you should import reactive from vue when you ues reactive.This is the vue3 feature. When you need to use something in vue, you must import it first.

import { reactive } from &#39;vue&#39;
const reactiveObject = reactive({ name: &quot;Object&quot;, id: &quot;443&quot;})

when you forget to import from vue, you cannot use it in template. This is incorrect syntax.

you should read more vue document, this is link

答案2

得分: 0

替换为 {{ props.info.name }},另外 <div> 那里缺少结束标签 </div>。

英文:

instead of {{ info.name }} try {{ props.info.name }}, also the <div> there is missing the end tag </div>

huangapple
  • 本文由 发表于 2023年8月10日 17:30:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/76874420.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定