【问题标题】:Vue3: Displaying of nested JSON object data does not workVue3:嵌套 JSON 对象数据的显示不起作用
【发布时间】:2021-11-25 04:59:14
【问题描述】:

我正在尝试显示来自嵌套 JSON 对象的数据。从 axios 正确检索数据,但我没有显示它。

json 对象如下所示:

{
        "id": "1",
        "name": "Germany",
        "continent": "Europe",
        "president": {
            "id": "12",
            "name": "Joanna Doe",
        }
}

在 vue 组件中,数据保存在“国家”对象中。

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

有没有办法渲染这些嵌套数据?

谢谢!

【问题讨论】:

    标签: javascript vue.js axios vuejs3


    【解决方案1】:

    country 最初是一个空对象(后来更新),但您的模板尝试立即呈现嵌套属性:

    <p>{{ country.president.name }} </p>
    

    这样会报错,因为country.president最初是不存在的,所以是undefined,导致从undefined读取name出错。

    解决此问题的一种方法是 conditionally render 仅在定义 country.president&lt;p&gt;

    <p v-if="country.president">{{ country.president.name }}</p>
    

    或者使用 Vue 3,您可以使用 optional chaining 来避免运行时错误。但是,&lt;p&gt; 元素仍会以空主体呈现。 (如果不需要空标签,请坚持上面的条件渲染方案。)

    <p>{{ country.president?.name }}</p>
    

    【讨论】:

      【解决方案2】:

      "continent": "Europe" 后面缺少一个逗号 ,

      您的代码应该可以工作。 See this example

      【讨论】:

      • 我认为这只是问题中的错字。否则,OP 会在看到 TypeError 之前得到 SyntaxError
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-27
      • 2015-10-27
      • 2017-12-02
      • 2018-03-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多