【问题标题】:Vuejs will not render component correctly when trying to loop thru array data or v-for尝试通过数组数据或 v-for 循环时,Vuejs 将无法正确呈现组件
【发布时间】:2016-06-14 04:48:47
【问题描述】:
        <!DOCTYPE html>
    <html lang="en">
    <head>
        <script src="js/vue.js"></script>

        <meta charset="UTF-8">

        <title>V-for example</title>

    </head>
    <body>
    <script type="x/template" id="testTemplate">

        <div><h1>{{name}}</h1>

            <p>{{Age}}</p></div>
    </script>
    <div id="example">


        <div id="filler">
    <template v-for="person in people">
    <test-component name="{{person.name}}"></test-component>
</template>
        </div>
    </div>


    <script>

        var newComponent = Vue.extend({
            template: '#testTemplate',
            props: ['name'],
            data: function () {
                return {
                    Age: 1010
                }
            }
        });
        Vue.component('test-component', newComponent);


        new Vue({
            el: '#example',
            data: {
                people: [{
                    name: 'jason',
                    age: 15,
                    complete: true
                }, {
                    name: 'Jeremy',
                    age: 20,
                    complete: false
                }]


            },
            ready: function () {
                var divoutput = document.querySelector('#filler');
                alert(divoutput.innerHTML);
                len = this.$data.people.length;
                for (i = 0; i < len; i += 1) {
                    var nameT = this.$data.people[i].name;

                    divoutput.innerHTML += '<test-component name="' + nameT + '"></test-component>';

                }

            },

        });


    </script>

    </body> </html>

我试图在 Vue.ready() 函数期间将 Vue 数据数组中的所有人都注入到组件中,并将其添加到 div 的 innerHTML 中。我表明结果被注入到“填充”数组中,但它们本身的组件没有被正确渲染。如果我制作我的组件的手动实例,它工作正常。

【问题讨论】:

    标签: javascript components vue.js


    【解决方案1】:

    您不应该尝试使用innerHTML 添加 Vue 组件。那就是自己管理 DOM,让 Vue 自己来做。这是一个小提琴:

    https://jsfiddle.net/xccjsp4b/

    我将脚本模板更改为 div,因为我不确定您是否可以使用这样的脚本标签(尽管我可能是错的)。然后您只需使用v-for 循环访问人员并将相关数据作为属性传递。如果每个人都有自己的年龄,你希望它是一个属性而不是数据变量。

    另外,使用:name="person.name" 的速记绑定而不是name="{{person.name}}": 告诉 Vue 评估表达式。

    【讨论】:

    • 谢谢,我一发布(当我使用 innerHTML 时)我意识到我应该使用 v-for 直到我使用 :name 版本之前它仍然无法工作 - 仅供参考但脚本模板版本确实有效。感谢您的帮助!
    • 只是为了我自己的记录,我在 api 中包含了这个速记:vuejs.org/guide/syntax.html#Shorthands
    • 非常感谢您。我不知道如何将信息从主应用程序传递到组件。我在组件元素上有'v-for',但是查看您的示例,我发现我需要在组件元素周围的元素中使用它。太棒了!
    猜你喜欢
    • 1970-01-01
    • 2021-02-01
    • 1970-01-01
    • 2014-07-24
    • 1970-01-01
    • 1970-01-01
    • 2019-04-29
    • 2018-12-19
    • 1970-01-01
    相关资源
    最近更新 更多