2017-05-05 325 views
0

我使用Vue.js填充位置列表,並使用應該返回使用該地址的格式化地圖鏈接的方法。Vue.js方法在訪問數據時返回undefined

問題是,在該方法中,試圖返回this.Address結束於未定義。下面是我得到了什麼:

// the Vue model 
pbrplApp = new Vue({ 
    el: '#pbrpl-locations', 
    data: { 
     'success' : 0, 
     'errorResponse' : '', 
     'wsdlLastResponse' : '', 
     't' : 0, 
     'familyId' : 0, 
     'brandId' : 0, 
     'srchRadius' : 0, 
     'lat' : 0, 
     'lon' : 0, 
     'response' : [] 
    }, 
    methods: { 
     getDirections: function(address,city,st,zip){ 
      // THIS Doesn't work: 
      //var addr = this.Address + ',' + this.City + ',' + this.State + ' ' + this.Zip; 
      var addr = address + ',' + city + ',' + st + ' ' + zip; 
      addr = addr.replace(/ /g, '+'); 
      return 'https://maps.google.com/maps?daddr=' + addr; 
     } 
    } 
}); 


// the template 
<ul class="pbrpl-locations"> 
<template v-for="(location,idx) in response"> 
    <li class="pbrpl-location" :data-lat="location.Latitude" :data-lon="location.Longitude" :data-premise="location.PremiseType" :data-acct="location.RetailAccountNum"> 
     <div class="pbrpl-loc-idx">{{idx+1}}</div> 
     <div class="pbrpl-loc-loc"> 
      <div class="pbrpl-loc-name">{{location.Name}}</div> 
      <div class="pbrpl-loc-address"> 
       <a :href="getDirections(location.Address,location.City,location.State,location.Zip)" target="_blank"> 
        {{location.Address}}<br> 
        {{location.City}}, {{location.State}} {{location.Zip}} 
       </a> 
      </div> 
     </div> 
    </li> 
</template> 
</ul> 

現在,我有通過地址,城市,州和郵編回到模型的方法,我知道錯了 - 但我無法找到vue.js文檔中有關正確獲取值的任何內容。

讓方法正確引用「this」的正確方法是什麼?謝謝你的幫助。

+0

你在'data'中似乎沒有'Address','City','State'等屬性,那麼爲什麼你會期望它們不是'undefined'? – Phil

回答

1

this.Address不起作用,因爲Address不是您的數據的一部分。它看起來像你在做什麼迭代通過response,以某種方式填充位置。

可能只是通過locationgetDirections而不是每個參數。

getDirections(location){ 
    let addr = location.Address+ ',' + location.City + ',' + location.State + ' ' + location.Zip 
    .... 
} 

,改變你的模板

<a :href="getDirections(location)" target="_blank"> 

一般來說,在Vue的方法,this將參照Vue公司本身,這意味着是在Vue公司(其性質定義定義的任何財產包括data)將可通過this訪問(禁止在方法內部錯誤捕獲this)。對於您的情況,您可以參考getDirectionsthis的任何成功,errorResponse,wsdlLastResponse,t,familyId,brandId,srchRadius,lat,lon或響應。

+0

好的,謝謝!我知道這是我錯過的東西。我正在從Knockout遷移,而且情況有點不同。謝謝! –