Skip to content

Instantly share code, notes, and snippets.

@windsting
Last active June 3, 2017 10:09
Show Gist options
  • Save windsting/a51b9f0011a7ea266b7675de1ff8feeb to your computer and use it in GitHub Desktop.
Save windsting/a51b9f0011a7ea266b7675de1ff8feeb to your computer and use it in GitHub Desktop.
Mind 'this' in Vue or anywhere

Here is the index.html

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

The main.js -- the working version

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

The main.js -- the non-working version

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)

How to make correct the later version?

The variable 'vue' is defined to do this, just replace 'this' to 'vue', aka change this.users = response.data; to vue.users = response.data; .

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment