vue子组件template不能再写子组件了吗

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="https://unpkg.com/vue/dist/vue.js"></script>
</head>
<body>
    <div id="dr01">
        <child01></child01>
    </div>

    <script>
        Vue.component("child01", {
            data: function() {
                return {
                    cMsg: "this is child msg!",
                    cParentMsg: this.$parent.dr01Msg, //child01的上级信息就是dr01的dr01Msg
                    cRootMsg: this.$root.rootMsg, //child01的根信息就是dr01的rootMsg
                }
            },
            template: "<div>cMsg: {{cMsg}}, cParentMsg: {{cParentMsg}}, cRootMsg: {{cRootMsg}}</div>"
                +"<grandson01 :s-parent-msg='cMsg'></grandson01>"
        });
        //自定义孙代组件grandson01,
        Vue.component("grandson01", {
            data: function() {
                return {
                    sMsg: "this is grandsonMsg1",
                    sRootMsg: this.$root.rootMsg, //grandson01根信息就是dr01的rootMsg
                }
            },
            //grandson01上级信息就是child01的cMsg,
           //在这里使用props属性,将子代cMsg赋给孙代的“sParentMsg”,示例:在子代模板中:<grandson01 :s-parent-msg='cMsg'></grandson01>
            props:["sParentMsg"],
            template: "<div>sMsg: {{sMsg}}, sParentMsg: {{sParentMsg}}, sRootMsg: {{sRootMsg}}</div>"
        })
        var dr01 = new Vue({
            el: "#dr01",
            data: {
                dr01Msg: "this is dr01Msg!",
                rootMsg: "this is rootMsg!",
            },
        });
    </script>
</body>
</html>

我在child01子组件的template里又加了grandson01组件 可是页面不显示grandson01组件内容 还报了一个警告:

vue.js:525 [Vue warn]: Component template should contain exactly one root element:

<div>cMsg: {{cMsg}}, cParentMsg: {{cParentMsg}}, cRootMsg: {{cRootMsg}}</div><grandson01 :s-parent-msg='cMsg'></grandson01>

If you are using v-if on multiple elements, use v-else-if to chain them instead

求各位指教

阅读 28.3k
2 个回答

错误提示很清楚了:

Component template should contain exactly one root element

只能有一个根元素 <div>abcde....<grandson01 ></grandson01></div>,不能 <div>abcde....</div><grandson01></grandson01>

新手上路,请多包涵

解决办法:

将<template>中的元素用一个<div>包裹起来即可。

推荐问题
宣传栏