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!

1
  • Use a closure or bind or a fat arrow function to capture the correct 'this' for your promise callback. Commented Apr 3, 2017 at 3:54

2 Answers 2

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

See How to access the correct this inside a callback?

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

Comments

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);
  });
  },
}

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.