我如何在方法中访问vuejs数据

时间:2017-07-09 12:03:49

标签: javascript arrays laravel-5 vue.js momentjs

我已经使用laravel中的ajax请求将数据库中的数据集合保存到vue.js中的数组中。我想从一个方法中获取该集合中的一些数据,以便我可以为正文创建更多数据,但不知何故我无法访问它。例如,使用下面的代码。

var vm = this;
$.get('url', function (response) {
      vm.time_slots = response;
      for( i=0; i < vm.time_slots.length; i++){  //also tried with var/let i
         if(i=0){
            console.log(vm.time_slots[i].start_time);
         }else if(vm.time_slots[i].start_time > vm.time_slots[i-1].start_time){
           console.log(vm.time_slots[i].start_time);
         }
      }
     }, 'json');

我得到了解开。但如果我通过控制台访问它我得到我需要的东西。以下是数据。

data: {
  time_slots: [],
  current_timeslots: []
},

现在time_slots中的每个time_slot都有一个start_date end_date等。我想访问它们但我得到了未定义。甚至 this.time_slots.length 返回为0,而如果我在控制台中检查我得到12。 如何在方法中访问数据。

2 个答案:

答案 0 :(得分:0)

$.get执行异步 HTTP请求。您从该请求返回的数据仅在回调函数中可用。

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]);

了解AJAX请求的工作方式非常重要,尤其是在JavaScript中执行此类HTTP请求的异步性质。

您应该在上面的代码中的各个位置放置断点,并逐步浏览浏览器调试器中的执行路径,看看它是如何工作的。

这是另一个(更简单的)示例,演示了它的工作原理:

var data = 'hello';

setTimeout(function() {
  data = 'world';
  console.log('inside callback: ' + data);
}, 1000);

console.log('outside callback: ' + data);

答案 1 :(得分:0)

我认为似乎更多关于异步问题而不是Vuejs问题。您只需要记住异步调用在javascript中的行为方式。异步调用将执行它的任务而不会阻塞下一行代码。换句话说,异步调用几乎会在下一行代码执行的同时执行。对于你的情况:

$.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'

为什么从控制台访问会返回数据?这是因为在您访问控制台之前,$ .get已经完成。如果你运气不好或$ .get需要更多的时间来完成访问控制台的时间,你就无法获得数据

希望这可以提供帮助