Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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',
});
like image 572
chrisg86 Avatar asked Apr 20 '16 14:04

chrisg86


People also ask

How do I make reusable components Vue?

Each component you create in your Vue app should be registered so Vue knows where to locate its implementation when it is encountered in a template. To register your component in another component, you should add it to the components property in the Vue object.

What is VueUse?

VueUse is a collection of utility functions based on Composition API. We assume you are already familiar with the basic ideas of Composition API before you continue.


1 Answers

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>
like image 88
chrisg86 Avatar answered Nov 13 '22 23:11

chrisg86