vue2.0如何嵌套组件

<div id="app">
    <parent-component>        
    </parent-component>
</div>

<template id="parent-component">
    <child1></child1>
    <child2></child2>
    <button @click="showChildComponentData">显示子组件数据</button>
</template>

<template id="child-component1">
    <h2>{{ msg }}</h2>
</template>

<template id="child-component2">
    <h2>{{ msg }}</h2>
</template>

在2.0中这样使用浏览器会报错:[Vue warn]: Component template should contain exactly one root element:
缺少根元素?我试了下好像只有2.0才会报错,这是什么原因?
补上js代码:

Vue.component('parent-component',{
        template: '#parent-component',
        components: {
            'child1': {
                template: '#child-component1',
                data: function(){
                    return {
                        msg: 'child1'
                    };
                }
            },
            'child2': {
                template: '#child-component2',
                data: function(){
                    return {
                        msg: 'child2'
                    };
                }
            }
        },
        methods: {
            showChildComponentData: function(){
                for( var i = 0;i < $children.lenth;i++) {
                    alert($children[i].msg);
                }
            }
        }
    });
    new Vue({
        el: '#app'
    });
阅读 10.4k
2 个回答

从2.0开始,每个组件必须只有一个根元素。不再允许片段实例。 参考文档:迁移指南#模板

<template id="parent-component">
<div>

<child1></child1>
<child2></child2>
<button @click="showChildComponentData">显示子组件数据</button>

</div>
</template>

刚看到,其实这个错误你自己看报错信息是能够改出来的。他说组件下应该包含一个根元素,你就可以想到,给children1和children2包一个div就行

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题