0

I got the following sample code, if I use:

 <p>{{usr[0]}}</p>

works, but if I refer to title, I got a 'unncaught TypeError: Cannot read property 'title' of undefined':

 <p>{{usr[0].title}}</p>

ncaught TypeError: Cannot read property 'title' of undefined

a sample code

what is the right way to handle this case? thanks

2 Answers 2

1

The quickest way is to use a v-if to determine whether to render to the content.

<p v-if="usr[0]">{{usr[0].title}}</p>

const TodoList = {
  data() {
    return {
      usr: []
    }
  },
  async mounted() {
    const response = await fetch('https://jsonplaceholder.typicode.com/todos');
    let rslt = await response.json();
    this.usr = rslt
  }
}
const app = Vue.createApp(TodoList)
app.mount('#myapp')
<script src="https://unpkg.com/vue@next"></script>
<!-- page content -->
<div id="myapp">
  <p v-if="usr[0]">{{usr[0].title}}</p>
</div>

You can also use another variable to track whether the content is ready.

Sign up to request clarification or add additional context in comments.

Comments

1

Initially your array is empty and there's no property called title in the item at index 0 of your array, so you could add some conditional rendering like :

 <p>{{usr.length && usr[0].title}}</p>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.