Vue.js组件嵌套和template外用

Vue.extend组件的嵌套和template外用

组件嵌套分为全局组件嵌套和局部组件嵌套

  • 组件嵌套需要将子元素写在父元素内
  • 子组件必须在父组件中注册之后才能在父组件的模板中使用

全局组件嵌套

Vue.component('Father',{
    template: '<h3> father <Son></Son> </h3>'//这里要把子组件加进来
})
Vue.component('Son',{
    template: '<h3> son </h3>'
})

new Vue({
    el: '#app',
})

局部组件嵌套

new Vue({
    el: '#app',
    components: {
        'Father': {
            template: '<div> father <Son/> </div>',//这里也要把子组件加进来,组件可以使用单标签
                components: {
                'Son': {//子组件必须在父组件内创建才行
                    template: '<h3> Son </h3>'
                }
            }
        }
    }
})

template的外用

注意:template外用,组件模板中的第一个元素必须唯一

<body>
    <div id="app">
        <Hello></Hello><!---在组件模板中调用之后还要在根实例模板中调用一下--->
    </div>
    
    
    <template id="Hello">
        <div class="content"><!---这个元素必须唯一的--->
            <ul>
                <li><a href="">你好</a></li><!---里面的子元素可以多个--->
                <li><a href="">你好</a></li>
                <li><a href="">你好</a></li>
            </ul>
        </div>
    </template>
</body>
Vue.component('Hello',{
    template: '#Hello'//这里的作用相当于根实例中的el:'app' ;作用一样,都是挂载
})

new Vue({
    el: '#app',
})

摘自:

https://blog.csdn.net/zhangyuea/article/details/89421424

原文地址:https://www.cnblogs.com/pengchenggang/p/12037721.html