Vue 初始化数据报错TypeError: Cannot read property 'xxx' of undefined

在Vue项目中,数据渲染成功,但控制台报错

[Vue warn]: Error in render: "TypeError: Cannot read properties of undefined (reading 'skuDesc')"

found in

---> <Detail> at src/views/Detail/index.vue
       <App> at src/App.vue
         <Root>

例如:

<template>
    <p class="news">
        {{ goodsInfo.skuInfo.skuDesc }}
    </p>
</template>

<script>
computed: {
    ...mapState({ goodsInfo: state => state.detail.goodsInfo })
}
</script>

出现错误原因:在页面初始化的时候,由于数据数从Vuex异步拿过来的,所以页面的skuDesc左侧数据是空的,就出现undefined.skuDesc这种情况,产生Cannot read property 报错

解决办法:

1、使用v-if先判断数据是否存在。

为哈不用v-show

因为v-if不满足时,后面代码不会解析,可以避免报错

v-show不管是否满足都会解析,还是会出现报错

<p class="news" v-if="goodsInfo.skuInfo">
    {{ goodsInfo.skuInfo.skuDesc }}
</p>

2、在从Vuex中拿数据时,用getters处理一下,使用mapGetters()拿数据

getters处理时返回值用

return state.goodsInfo || {}