简体   繁体   中英

VueJS nested components

I created a vue component, which has an initial ajax call that fetches an array of objects that i will be looping through. Is there a way to define/cast these objects as another vue component? This is what i got so far:

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

For completeness I will post the answer to my own question here.

All the credit goes to Joseph Silber and Jeff

Code from 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',
});

Code from 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM