0

I'm trying to loop through a set of users from jsonplaceholder API.

Here is my Vue component:

new Vue({
  el: "#vue-app",
  data: {
    name: "dani",
    thumbnail: '',
    users: []
  },
  beforeMount() {
    axios.get('https://jsonplaceholder.typicode.com/users')
      .then(function (response) {
        this.users = response.data
        console.log("users: ", this.users[0])
      })
      .catch(function (error) {
        console.log(error)
      })
  }
})

And here is the vue-app div in HTML page:

<div id="vue-app">

    <div class="row">

        <div class="col-sm-4" v-for="user in users">
          <div class="card-body">
            <h4 class="card-title">{{ user.name }}</h4>
            <p class="card-text">{{ user.email }}</p>
            <a href="#" class="card-link">Card link</a>
            <a href="#" class="card-link">Another link</a>
          </div>
        </div>

    </div>

  </div>

Loop doesn't pulls and displays anything. How to load users array to v-for properly?

Here is the JSFiddle for the same : https://jsfiddle.net/danimvijay/9gupydws/

Dani Vijay
  • 2,188
  • 2
  • 22
  • 37

1 Answers1

3

this in your function is undefined. In vue life cycle methods, created, mounted..., Vue has already bound this instance for us. But in function in axios.get().then(function()), this is not bound.

You might want to do

  beforeMount() {
    console.log('Before mount')
    const vm = this
    axios.get('https://jsonplaceholder.typicode.com/users')
      .then(function (response) {
        vm.users = response.data
        console.log("users: ", vm.users[0])
      })
      .catch(function (error) {
        throw error
      })
  }

or you can use es6 syntax

 beforeMount() {
    console.log('Before mount')
    axios.get('https://jsonplaceholder.typicode.com/users')
      .then((response) => {
        this.users = response.data
        console.log("users: ", this.users[0])
      })
      .catch(function (error) {
        throw error
      })
  }

In arrow function, this is bound to lexical context, which mean it's same with this in created

ittus
  • 21,730
  • 5
  • 57
  • 57