0
<!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!

Tom Hanks
  • 594
  • 1
  • 5
  • 21
  • Use a closure or bind or a fat arrow function to capture the correct 'this' for your promise callback. – Bert Apr 03 '17 at 03:54

2 Answers2

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

See How to access the correct this inside a callback?

Bert
  • 80,741
  • 17
  • 199
  • 164
1

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);
  });
  },
}
Eric Guan
  • 15,474
  • 8
  • 50
  • 61