2016-04-20 15 views
7

Ho creato un componente vue, che ha una chiamata Ajax iniziale che recupera una matrice di oggetti che eseguirò il looping. C'è un modo per definire/lanciare questi oggetti come un altro componente Vue? Questo è quello che ho ottenuto finora:Componenti innestati 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

Lo fate nel modello. '' –

+0

Il modo 'vue' per fare ciò, è aver definito in precedenza il componente, in modo da popolare solo i dati e visualizzarlo con 'v-if' /' v-show' se hai solo un componente da mostrare o con 'v-for' se hai molti componenti da mostrare –

+0

Grazie per le tue risposte. Come posso accedere alla variabile 'item' nel componente figlio, quando si va con la soluzione di Josephs? Non sembra essere disponibile nel modello secondario. – user2968356

risposta

12

Per completezza posterò la risposta alla mia domanda qui.

Tutto il merito va a Joseph Silber e Jeff

Codice da 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', 
}); 

Codice da 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> 
Problemi correlati