繁体   English   中英

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

[英]how can i access vuejs data in method

我已经使用vue.js中的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。我如何使用该方法访问数据。

$.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);

我认为它似乎比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需要比访问控制台更多的时间来完成操作,那么无论如何您都不会获得数据

希望这可以帮助

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM