简体   繁体   中英

Vuejs will not render component correctly when trying to loop thru array data or v-for

        <!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>

I'm trying to take all of the people in the Vue data array and inject it into a component and add it to a innerHTML of a div during the Vue.ready() function. I show that result is being injected in to the "filler" array but the components them selves are not being rendered properly. If I make a manual instance of my component it works fine.

You shouldn't try to add Vue component using innerHTML . That's managing the DOM yourself, just let Vue do that on its own. Here is a fiddle:

https://jsfiddle.net/xccjsp4b/

I changed the script template to a div because I'm not certain you can use the script tag like that (although I could be wrong). Then you just use a v-for to loop through the people and pass the relevant data as properties. If each person is going to have their own age, you want it to be a property not a data variable.

Also, use the shorthand binding of :name="person.name" rather than name="{{person.name}}" . The : tells Vue to evaluate the expression.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM