VueJS嵌套组件

12

我创建了一个Vue组件,它有一个最初的AJAX调用,获取一个对象数组,我将通过循环遍历这些对象。是否有一种方法将这些对象定义/转换为另一个Vue组件?这是我目前的进展:

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
你可以在模板中这样写:<child-component v-for="item in list"></child-component> - Joseph Silber
Vue 的做法是,先定义好组件,然后通过填充数据并使用 v-if/v-show 显示单个组件,或者使用 v-for 显示多个组件。 - Yerko Palma
感谢您的回复。如果按照Joseph的解决方案,我如何在子组件中访问item变量?它似乎在子模板中不可用。 - chrisg86
一些更多的细节:父组件是一个表格,子组件是一个tr元素。这可以用来打印基本布局,但不能将变量传递给子组件:<tr is="child-component" v-for="item in list"></tr> - chrisg86
1
将item变量传递进来,像这样<tr is="child-component" v-for="item in list" :item="item"></tr> - Jeff
感谢您的帮助,将该项作为属性传递解决了问题。我会归纳您的评论并在新答案中总结。 - chrisg86
1个回答

16

为了完整起见,我将在此发布自己问题的答案。

所有功劳归给Joseph SilberJeff

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

来自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>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接