[Vue warn]:Error in render: “TypeError: Cannot read property ‘0’ of undefined”

Error description
I defined the seller data in the Vue component. The seller requests a JSON file through Axios. In the seller, there is a data support of array type, as follows:
//

{
"data":{
     "supports": [
          {
            "type": 0,
            "description": "Pay online with 28 or more for 5 off"
          },
          {
            "type": 1,
            "description": "20% off all VC Infinity Orange Juice"
          },
          {
            "type": 2,
            "description": "Single exciting package"
          }
    }
}

I want to get the data of “Pay online with 28 or more for 5 off” to render my elements. I use seller supports[0].description is as follows:

<template>
      <div class="suppor">
        <span>{{seller.supports[0].description}}</span>
      </div>
</template>
<script>
export default {
  name: 'Header',
  data () {
  return: {
    seller: { }
   }
  }
}
</script>

According to the above method, although I rendered the element as scheduled, I reported the following errors and warnings on the browser console.

Solution:
Add a v-if directive to the element to be rendered to determine if there is content in this array, and the warning will be lifted, because the span I want to render is contained in the div, so I add a judgment directive to the div

      <div v-if="seller.supports" class="suppor">
        <span>{{seller.supports[0].description}}</span>
      </div>

Principle Explanation.
After we define seller data in data() method, the initial data will be passed to the component first, before axios request to the data, the component will read the data in seller and render it, but at this time seller is an empty object, seller.supports is also undefined, so if I use [0], it will report a typeerror error, but after that, axios requests the data and the element is rendered further, but the console error warning is still there.
When I add a judgment, I prevent the behavior of taking a value with an index to a ubdefined value.

Similar Posts: