vue学习—组件

  1. 如下代码,建立父子组件关系时报错: Component template should contain exactly one root element. If you are using v-if on multiple elements, use v-else-if to chain them instead.  这个错误翻译为:模板语法错误组件模板应该正好包含一个根元素,如果你使用的是v-if多元素,使用v-else-if链他们。错误原因在于vue模板只支持一个元素,不能并列包含两个及以上,也就是说在worldWorld这个父组件中,template选项里面不应该同级地包含多个标签元素,把<city></city>元素放在p标签里面或者把p元素与city元素同时放进一个div里面就Ok了,这样就建立了Vue实例(爷爷)—>worldWorld父组件(父亲)—>city子组件(孙子)之间的关系。
    < body>
    < h1>组件03</ h1>
    < div id= "app">
    < world></ world>
    </ div>
    < script>
    city = {
    template: "<div>This is my home city!</div>",
    }
    worldWorld = {
    template: `
    <p>父子组件关系的搭建</p>
    <city></city>
    `,
    components: {
    "city": city
    }
    }
    var app = new Vue({ //初始化根实例
    el: "#app",
    data: {
    message: "xsdsfds"
    },
    components: {
    "world": worldWorld
    }
    })
    </ script>
    </ body>
  2. 通过使用Vue内置的component标签动态改变模板 ,并对其  is  特性进行动态绑定,你可以在同一个挂载点动态切换多个组件:
    < body>
    < h1>组件04</ h1>
    < div id= "app">
    < component : is= "who"></ component>
    </ div>
    < script>
    pA = {
    template: "<div>this is pA</div>",
    data: function () {
    return {
    a: 11
    }
    }
    };
    pB = {
    template: "<div>this is pB</div>"
    };
    pC = {
    template: "<div>this is pC</div>"
    };
    pD = {
    template: "<div>this is pD</div>"
    }
    var app = new Vue({ //初始化根实例
    el: "#app", //爷爷
    data: {
    who: "pB"
    },
    components: {
    "pA": pA,
    "pB": pB,
    "pC": pC,
    "pD": pD
    }
    })
    </ script>
    </ body>

  3. 代码如下,使用Vue内置的component标签动态改变模板时容易出现的错误:Component template requires a root element, rather than just text. 错误翻译:组件模板需要一个根元素,而不仅仅是文字。所以这时只要给pA的template选项加上一个根元素标签如"<div>this is pA{{a}}</div>"即可>。
    < body>
    < h1>组件04</ h1>
    < div id= "app">
    < component : is= "who"></ component>
    </ div>
    < script>
    pA = {
    template: "this is pA{{a}}",
    data: function () {
    return {
    a: 11
    }
    }
    };
    var app = new Vue({
    el: "#app",
    data: {
    who: "pA"
    },
    components: {
    "pA": pA
    }
    })
    </ script>
    </ body>

猜你喜欢

转载自blog.csdn.net/qq_38698753/article/details/79971765