VueJS嵌套组件 [英] VueJS nested components

查看:177
本文介绍了VueJS嵌套组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个vue组件,它有一个初始的ajax调用,用于获取我将循环遍历的对象数组。有没有办法将这些对象定义/转换为另一个vue组件?这是我到目前为止所得到的:

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.

所有功劳归功于 Joseph Silber 和< a href =https://stackoverflow.com/users/3720222/jeff>杰夫

来自main.js的代码

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

index.html的代码

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>

这篇关于VueJS嵌套组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆