簡體   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