2016-08-06 34 views
0

我正在通過Laravel將用戶數據傳遞給組件,這些數據包含以英里爲單位的距離,但是用戶可以選擇以km爲單位設置視圖距離,所以我必須通過profile.distance_mi來計算,我該如何實現?Vue.js在計算中得到v-for數組值

HTML:

<saved profiles="{{json_encode($profiles)}}" unit="{{Auth::user()->settings->unit}}"></saved> 

<div v-for="profile in profiles" class="col-xs-12 col-sm-4 col-md-3"> 
    ... 
    <h4>@{{distance}}</h4> 
    .... 
</div> 

JS

new Vue(
    { 
     el: 'body', 
     components: 
     { 
      saved: 
      { 
       template: '#saved', 
       props: ['profiles', 'unit'], 
       created: function() 
       { 
        this.profiles = JSON.parse(this.profiles); 
       }, 
       computed: 
       { 
        distance: function() 
        { 
         var unit = this.unit; 
         return unit == 0 ? Math.round(distance * 1.60934) + ' km' : distance + ' miles'; 
        } 
       } 
      } 
     } 
    }); 

回答

1

像這樣的計算的屬性不會在一個組件上的循環工作。

我認爲最簡單的方法來實現你想要實現的是做出另一個組件。我有點不清楚哪個屬性你要觀察,什麼不可以,但我認爲這將讓你在正確的方向:

面距離構件

var ProfileDistance = Vue.extend({ 
    props: ['profile'], 
    template: '<span>{{distance}}</span>', 
    computed: { 
    distance: function() { 
     if (this.profile.hasOwnProperty('distance_mi')) { 
     return this.profile.distance_mi + ' miles away'; 
     } else if(this.profile.hasOwnProperty('distance_km')){ 
     return this.profile.distance_km + ' kilometers away'; 
     } else { 
     return 'Distance N/A'; 
     } 
    } 
    } 
}) 

當然使確保你使用這個組件內現有saved組件的

components: { 
    //.... 
    'profile-distance': ProfileDistance 
} 

然後,只需將您的profile作爲一個屬性您profile-distance組件:

<profile-distance :profile="profile"></profile-distance> 

here's a working jsfiddle

+0

輪廓陣列具有distance_mi鍵而用戶陣列具有單元密鑰,如果該單元是0,則在KM用戶觀看並將其轉換英里KM,沒有distance_mi在profiles數組中,我需要在迭代數組的同時進行轉換,這就是爲什麼我使用計算屬性並將單元傳遞給Vue實例的原因,我只需要在組件中獲得距離,並且我應該很好那裏。 – Jofran

+0

你是對的!畢竟它讓我走上了正確的軌道!只需要做一個嵌套的組件,我只是學習Vue,它有點複雜,但謝謝!有時你需要有人將你設置在正確的行中,嵌套的組件和數據綁定到父項,杜! – Jofran

+0

@Jofran完全明白,自從大約一週前,我對VueJS本人完全陌生,但我自己卻遇到了類似的問題。很高興我能幫上忙! – Ohgodwhy