vue.js - vue2.0如何嵌套组件

查看:168
本文介绍了vue.js - 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'
    });

解决方案

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

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

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

</div>
</template>

这篇关于vue.js - vue2.0如何嵌套组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆