2016-04-20 18 views
7

Utworzono komponent vue, który ma początkowe wywołanie ajax, które pobiera tablicę obiektów, przez które przechodzę. Czy istnieje sposób definiowania/rzutowania tych obiektów jako innego komponentu vue? Oto, co mam do tej pory:Komponenty zagnieżdżone VueJS

var myComponent = Vue.extend({ 
    template: '#my-component', 

    created: function() { 
     this.$http 
      .get('/get_objects') 
      .then(function(data_array) { 
       for (var i = 0; i < data_array.data.length; i++) { 
        var item = data_array.data[i]; 

        // <<-- How do i tell vue to cast another component type here?? 

       } 
      } 
     ); 
    } 
}); 

Vue.component('my-component', myComponent); 

new Vue({ 
    el: 'body', 
}); 
+2

to zrobić w szablonie. '' –

+0

Sposób "vue" to wcześniej zdefiniowany komponent, więc wystarczy wypełnić dane i wyświetlić je 'v-if' /' v-show', jeśli masz tylko jeden komponent do pokazania lub z 'v-for', jeśli masz wiele komponentów do wyświetlenia –

+0

Dzięki za twoje odpowiedzi. W jaki sposób mogę uzyskać dostęp do zmiennej 'item' w komponencie podrzędnym podczas korzystania z rozwiązania Josephs? Wygląda na to, że nie jest dostępny w szablonie podrzędnym. – user2968356

Odpowiedz

12

Dla kompletności zamieściłbym tutaj odpowiedź na moje własne pytanie.

Wszystko zasługa Joseph Silber i Jeff

kod z main.js

var myComponent = Vue.extend({ 
    template: '#my-component', 

    data: function() { 
     return { 
      objects: [] 
     } 
    }, 

    created: function() { 
     this.$http 
      .get('/get_objects') 
      .then(function(objects) { 
       this.objects = objects.data; 
      } 
     ); 
    } 
}); 

var myComponentChild = Vue.extend({ 
    template: '#my-component-child', 

    props: ['item'], 

    data: function() { 
     return { 
      item: {} 
     } 
    } 
}); 

Vue.component('my-component', myComponent); 
Vue.component('my-component-child', myComponentChild); 

new Vue({ 
    el: 'body', 
}); 

kod z index.html

<my-component></my-component> 

<template id="my-component"> 
    <table> 
     <thead> 
      <tr> 
       <th>Name</th> 
       <th>URL</th> 
      </tr> 
     </thead> 
     <tbody> 
      <tr is="my-component-child" v-for="item in objects" :item="item"></tr> 
     </tbody> 
    </table> 
</template> 

<template id="my-component-child"> 
    <tr> 
     <td></td> 
     <td>{{ item.name }}</td> 
     <td>{{ item.url }}</td> 
    </tr> 
</template>