0👍
$.get
performs an asynchronous HTTP request. The data you get back from that request is only available inside the callback function.
var vm = this;
$.get('url', function (response) {
// This code executes once the data is available
vm.time_slots = response;
// This works
console.log(vm.time_slots[0]);
}, 'json');
// This line executes immediately after the above HTTP request is
// sent but not yet resolved, so the data isn't available
console.log(vm.time_slots[0]);
It’s important to understand how AJAX requests work, in particular the async nature of performing such HTTP requests in JavaScript.
You should put breakpoints at various spots in the above code and step through the execution paths in the browser’s debugger to see just how it works.
Here’s another (simpler) example which demonstrates how this works:
var data = 'hello';
setTimeout(function() {
data = 'world';
console.log('inside callback: ' + data);
}, 1000);
console.log('outside callback: ' + data);
0👍
I think it seems more about asynchronous problem than Vuejs problem. You just need to remember how asynchronous call behave in javascript. Asynchronous call will execute it’s task without blocking the next line of code. In other words, asynchronous call will executed almost at the same time the next line of code executed. For your case:
$.get('url', function (response) {
// if you want to do operations (formatting data, do some calculation, or set your vue instance data) immediately after $.get returns data, put your operations inside this callback
}, 'json');
// this is the next line of code, and will be executed almost at the same time $.get executed
// if you put those operations here (outset $.get method), $.get method hasn't finished yet because asynchronous call need more time to finish, so you don't have any data to be processed at that time, that's why it show 'undefined'
Why accessing from console returns data? It’s because the $.get has already finished before you access your console. If you’re unlucky or $.get need more time to finish than the time you access the console, you wouldn’t get the data anyway
Hope this can help