【问题标题】:VueJS nested componentsVueJS 嵌套组件
【发布时间】:2016-08-13 06:34:08
【问题描述】:

我创建了一个 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',
});

【问题讨论】:

  • 您在模板中执行此操作。 &lt;child-component v-for="item in list"&gt;&lt;/child-component&gt;
  • vue 的方法是预先定义你的组件,所以你只需填充它的数据并用v-if/v-show 显示它,如果你只有一个组件要显示或v-for,如果你有很多组件要展示
  • 感谢您的回复。使用 Josephs 解决方案时,如何访问子组件中的 item 变量?它似乎在子模板中不可用。
  • 更多细节:父组件是一个表格,子组件是一个tr元素。这可以打印基本布局,但不能将变量传递给子组件:&lt;tr is="child-component" v-for="item in list"&gt;&lt;/tr&gt;
  • &lt;tr is="child-component" v-for="item in list" :item="item"&gt;&lt;/tr&gt;那样传入item变量

标签: javascript vue.js


【解决方案1】:

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

所有功劳归于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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-10
    • 2023-04-04
    • 2017-12-12
    • 2021-01-07
    • 1970-01-01
    • 2018-08-12
    • 2019-03-27
    • 2017-08-06
    相关资源
    最近更新 更多