2017-03-21 59 views
1

調用Ajax請求這是我目前使用的Vue 2.2.4有關Initializing Vue data with AJAXVueJs 2不會在「準備就緒」功能

。我在上面的例子中創建了一個Vue元素和「ready」塊內的ajax函數,但沒有渲染。沒有打印console.log表明這些ajax請求甚至沒有被調用。任何人都知道發生了什麼事?假設我必須爲此任務使用jQuery ajax庫。

下面是我的代碼:

var newJobsVue = new Vue({ 
    el: '#new-jobs', 
    data: { 
     jobs: [] 
    }, 
    methods: { 
     ready: function() { 
      var self = this; 
      return $.ajax({ 
      method: 'GET', 
      url: 'https://api.indeed.com/ads/apisearch', 
      crossDomain: true, 
      dataType: 'jsonp', 
      data: { 
       'v': '2', 
       'format': 'json', 
       'publisher': <My_Key>, 
       q: 'javascript', 
       l: '94112', 
       userip: 'localhost', 
       useragent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2)', 
       latlong: '1' 
      } 
      }) 
      .done(function(response){ 
      //render the jobs from the search_response 
      console.log("response is>>>>>", response.results); 
      //nope, this is not actually logged 
      self.jobs = response.results; 
      }) 
      .fail(function(error){ 
      console.log("error is>>>", error); 
      // neither is this one logged 
      }); 
     } 
    } 
    }); 

回答

2

你永遠不會調用ready。嘗試

var newJobsVue = new Vue({ 
    el: '#new-jobs', 
    data: { 
     jobs: [] 
    }, 
    methods: { 
     ready: function() { 
      // alot of code... 
     } 
    }, 
    mounted(){ 
     this.ready(); 
    } 
    }); 
+0

注意'ready()'實際上是一個生命週期鉤子,所以你可以像掛載()一樣使用它。他可能只是混淆了方法和生命週期鉤子。 –

+0

@woutr_be你的意思是在Vue 1? – Bert

+0

Vue 2.2.4應該支持https://vuejs.org/v2/api/#created –

0

您也可以使用初始化掛鉤created或比beforeCreate鉤運行後鉤您的數據:beforeMount, mounted在創建的鉤子中,您將獲得能夠訪問的方法,被動數據和事件處於活動狀態而在beforeCreate鉤子中無法訪問您的數據和方法。

簡介:使用創建掛鉤如果你想在最早的時間更多鈔票初始化數據使用跑得比beforeCreate hook後來鉤來初始化數據

var newJobsVue = new Vue({ 
    el: '#new-jobs', 
    data: { 
     jobs: [] 
    }, 
    methods: { 
     ready: function() { 
      your ready function 
     } 
    }, 

    created(){ // can also be replace with beforeMount and Mounted 
     this.ready(); 
    } 
    }); 

參考: