我正在尝试显示来自嵌套JSON对象的数据。可以正确地从axios中检索数据,但是我无法显示它。
json对象如下所示:
{
"id": "1",
"name": "Germany",
"continent": "Europe",
"president": {
"id": "12",
"name": "Joanna Doe",
}
}在vue组件中,数据保存在"country“对象中。
. . .
data() {
country: {},
}如果我随后尝试在vue模板中呈现它,如果我呈现如下,我将获得所有数据:
<p>{{ country }}</p>但是,如果我尝试呈现嵌套的“总统”属性的数据,如下所示:
<p>{{ country.president.name }} </p>我得到以下错误:
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'name')
at Proxy.<anonymous> (CountryDetail.vue:25)
at renderComponentRoot (runtime-core.esm-bundler.js:1165)
at componentEffect (runtime-core.esm-bundler.js:5184)
at reactiveEffect (reactivity.esm-bundler.js:42)
at effect (reactivity.esm-bundler.js:17)
at setupRenderEffect (runtime-core.esm-bundler.js:5137)
at mountComponent (runtime-core.esm-bundler.js:5096)
at processComponent (runtime-core.esm-bundler.js:5054)
at patch (runtime-core.esm-bundler.js:4660)
at componentEffect (runtime-core.esm-bundler.js:5191)有没有办法呈现这个嵌套的数据?
谢谢!
发布于 2021-10-04 23:23:10
country最初是一个空对象(后来被更新),但您的模板尝试立即在中呈现嵌套属性:
<p>{{ country.president.name }} </p>这会导致一个错误,因为country.president最初不存在,所以它是undefined,从而导致从undefined读取name的错误。
解决此问题的一种方法是仅在定义了country.president时才对该<p>执行conditionally render:
<p v-if="country.president">{{ country.president.name }}</p>或者使用Vue 3,您可以使用optional chaining来避免运行时错误。但是,<p>元素仍将呈现为空的正文。(如果不需要空标签,请坚持使用上面的条件渲染解决方案。)
<p>{{ country.president?.name }}</p>发布于 2021-10-04 19:49:14
您在"continent": "Europe" <-后缺少一个逗号,。
您的代码应该可以工作。See this example
https://stackoverflow.com/questions/69441558
复制相似问题