<!DOCTYPE html>
<html>
<head>
<title>Laravel vue2-step-by-step 18</title>
<!-- <link rel="stylesheet" href="./stylesheets/bulma.min.css" /> -->
<style>
body{
padding: 40px 80px;
}
</style>
</head>
<body>
<div id="app" class="container">
<h1 class="title">Vue ajax request</h1>
<ol class="content">
<li v-for="user in users" v-text="user.name"></li>
</ol>
</div>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://unpkg.com/vue"></script>
<script src="./javascripts/main.js"></script>
</body>
</html>
var jsonUrl = 'http://jsonplaceholder.typicode.com/users';
var vue = new Vue({
el:"#app",
data:{
users : [],
},
created(){
axios.get(jsonUrl).then(response => this.users = response.data);
// axios.get(jsonUrl)
// .then(function (response) {
// this.skills = response.data;
// console.log(this.skills);
// });
}
});
var jsonUrl = 'http://jsonplaceholder.typicode.com/users';
var vue = new Vue({
el:"#app",
data:{
users : [],
},
created(){
// axios.get(jsonUrl).then(response => this.users = response.data);
axios.get(jsonUrl)
.then(function (response) {
this.users = response.data;
console.log(this.users);
});
}
});
It takes me about 2 or 3 hours to find why the later one not working, the shortest answer is "'this' has been changed", to compare them:
working version | non-working version | |
---|---|---|
what is in .then() | arrow function(closure or lambda expression) | real function |
what is 'this' | the Vue instance | the window object |
'users' before 'this.users=response.data;' | [](the 'users in data') | undefined |
'data.users' after 'this.users=response.data;' | response.data | [](unchanged because of untouched) |
The variable 'vue' is defined to do this, just replace 'this' to 'vue',
aka change this.users = response.data;
to vue.users = response.data;
.