【问题标题】:Vue.js cannot read property of null/undefined of nested object in PropsVue.js 无法读取 Props 中嵌套对象的 null/undefined 属性
【发布时间】:2021-07-19 19:22:59
【问题描述】:

所以我从 axios 调用中获取了一个对象。我将对象传递给子元素。然后在该子元素中,我循环遍历对象以读取另一个嵌套对象的属性。在这里我收到警告说我正在尝试读取未定义/空的属性。我确实检查了控制台,并且我正确接收了所有内容,问题在于读取该嵌套属性。 错误

TypeError: Cannot read property 'username' of null

我收到的对象如下所示

{
    "images": [
        "1616575030315IMG-20210211-WA0003.jpg",
        "1616575030316IMG-20210211-WA0004.jpg",
        "1616575030316IMG-20210211-WA0000.jpg"
    ],
    "_id": "605afa36320a772cecc4ed85",
    "name": "Maman",
    "brand": "Zara",
    "user": {
        "email": [
            "zakisb97@gmail.com"
        ],
        "_id": "6061bd38ada425383cc8a5b2",
        "username": "zakisb97",
        "tel": "0560728063",
        "apropos": "salam123456",
    },
    "type": "Robes",
    "size": "M",
    "description": "Good to wear",
    "price": "150",
}

父组件:市场产品

    <div
        v-for="product in products"
        class=""
        :key="product.id"
    >
        <product-default :product="product"  />
    </div>

产品默认子组件

<h1>{{ product.user.username }}</h1> // results in undefined

export default {
    props: {
        product: {
            type: Object,
            require: true,
            default: () => {}
        },
    },
   data: () => ({
       // nothing here
    }),
  
}

【问题讨论】:

    标签: javascript html vue.js nuxt.js


    【解决方案1】:

    您可能在对象为undefined 时访问对象属性。 试试这个:

        <div
            v-for="product in products"
            class=""
            :key="product.id"
        >
            <product-default v-if="product" :product="product"  />
        </div>
    

    还有这个:

    <h1 v-if="product && product.user">{{ product.user.username }}</h1>
    

    【讨论】:

    • 同样的问题。我确实检查了我得到的数据。所有产品都定义了用户名属性。
    • 您确定所有产品都定义了user 属性吗?如果将其添加到h1 会怎样:v-if="product &amp;&amp; product.user"
    • 你说得对,我只是重新检查了导致用户不存在的问题。因为在开发时我确实从数据库中删除了他们的记录。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2023-03-11
    • 2017-05-16
    • 1970-01-01
    • 2018-10-11
    • 2017-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多