【问题标题】:How to create components in a loop?如何在循环中创建组件?
【发布时间】:2017-12-15 08:24:49
【问题描述】:

我有一个创建照片的项目。我希望每张照片都是一个 vue 组件。

我发送了一个 axios 请求,在回答之后我想一张一张地插入每张照片,但每张照片必须是一个 vue 组件。

 axios.get('/api/prepare?query='+encodeURIComponent(this.text))
                .then(function(result){
                    const result_data = result.data;
                    self.images = result_data.images;
                        let index = 0;
                        for(let image in result_data.images){
                            new Vue({
                                el : "#photo",
                                template : "Photo.vue",
                                data : {
                                    src : result_data.images[image].src,
                                    symbolId : image,
                                    photoId : result_data.images[image].photo_id,
                                    name : index
                                }
                            });
                            index++;
                        }

在我的模板中我有<div id="photo"></div>

但我在控制台中遇到错误

找不到元素:#photo

【问题讨论】:

    标签: vue.js


    【解决方案1】:

    首先,使用props 定义一个可重用组件,将数据向下传递给它:

    <script>
        Vue.component('my-photo-component', {
            template: `<img :src="image_source"/>`,
            props: ['image_source'],
            data: function() {
                return {
                    other: 'data'
                };
            }
        });
    </script>
    

    然后,我们可以在v-for 循环中使用这个组件:

    <script>
        new Vue({
            el: '#app',
            data: {
                photos: []
            }
        });
    </script>
    
    <div id="app">
        <div v-for="photo in photos">
            <my-photo-component :image_source="photo.src"></my-photo-component>
        </div>
    </div>
    

    上面显然遗漏了一些关键部分,比如你需要的实际数据。您将需要扩展这个玩具示例以实现您想要的。但这应该会将您推向正确的方向。

    【讨论】:

    • 我按照你说的做了,但现在在 cosole 中出现下一个错误“你正确注册组件了吗?对于递归组件,请确保提供“名称”选项。”
    • 很遗憾,如果没有看到更新的代码,我将无法提供反馈。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-17
    • 2020-09-16
    • 1970-01-01
    • 1970-01-01
    • 2010-09-08
    • 2014-06-19
    • 1970-01-01
    相关资源
    最近更新 更多