Tom Hanks
Tom Hanks

Reputation: 614

Vue.js - this.data not storing GET response

<!DOCTYPE html>
<html>
<head>
  <title>Welcome to Vue</title>
  <script src="https://unpkg.com/vue/dist/vue.js"></script>
</head>
<body>
  <div id="app">
    <button v-on:click="sendTime">Load</button>
  <div v-for="user in users">
    <p>{{ user.username }}</p>
  </div>
</div>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.js"></script>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
new Vue({
el: '#app',
data: {
  users: [
    { username: "billy" },
    { username: "ryan" }
  ],
},
methods: {
  sendTime : function () {
    axios.get('/api/users')
  .then(function (response) {
    console.log(response.data);
    this.users = response.data;
  })
  .catch(function (error) {
    console.log(error);
  });
  },
}
})
</script>

</body>
</html>

console.log returns -

Array [ Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, 15 more… ]

For some reason I can't seem to get this Array to assign to 'this.data'? When ever the button is clicked the only change is a new console.log, but the two default users in data are displayed. Any help would be greatly appreciated!

Upvotes: 0

Views: 462

Answers (2)

Bert
Bert

Reputation: 82489

axios.get(...).then(function(response){
      this.users = response.data;
}.bind(this))

See How to access the correct this inside a callback?

Upvotes: 2

Eric Guan
Eric Guan

Reputation: 15982

You can maintain a reference to the Vue object, then use that reference within the callback.

methods: {
  sendTime : function () {
    var self = this;
    axios.get('/api/users')
  .then(function (response) {
    console.log(response.data);
    self.users = response.data;
  })
  .catch(function (error) {
    console.log(error);
  });
  },
}

Upvotes: 1

Related Questions