Vue.js多重组件嵌套

Vue.js多重组件嵌套

Vue.js中提供了很是棒的组件化思想,组件提升了代码的复用性.今天咱们来实现一个形如html

<app>
    <app-header></app-header>
    <app-content></app-content>
    <app-footer></app-footer>
</app>

的一个复合组件vue

1.js部分(component.js)

(function () {
    Vue.component('app',{
        template:'<div class="container"><div class="topBar">这个地方在渲染后不会被占用</div><slot></slot></div>'
    });
    Vue.component('app-header',{
        template:'<div class="header" slot="header">this is header</div>'
    });
    Vue.component('app-content',{
        template:'<div class="content">this is content</div>'
    });
    Vue.component('app-footer',{
        template:'<div class="footer">this is footer</div>'
    });
    var myApp=new Vue({
        el:'#myApp'
    });
})()
代码解释:
1. Vue.component定义了一个组件,其中的'app'是组件的名称,能够在html代码中直接把它当成一个标签来使用
2. template表示这个组件实际由什么html代码组成,能够直接在解释中写,也能够写一个ID,而后再html代码中写一个template模板,模板的ID就是此处写的ID,形如:
//js代码
Vue.component('app-header',{
        template:'#headerTemplate'
    });
//html代码
<template id="headerTemplate">
    <div class="header" slot="header">this is header</div>
</template>
3. 咱们要把app-header,app-content,app-footer这些子组件都放在app里面装起来,若是app这个组件内部也有多个元素,那么Vue怎么知道你须要把这些子组件放在app的哪一个位置呢?因此咱们须要在app的模板中指定一个slot,意思就是,其余组件都放在它里面,而不要去填充其余元素
注意事项:实例化myApp必定要放在组件注册以后,不然会报错哦

2.html部分

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>多重组件嵌套</title>
<style>
    .container{
        width: 500px;height: 190px;margin: 100px auto;text-align: center;
        font-family: 微软雅黑;
    }
    .topBar{
        height: 40px;line-height: 40px;background-color: #4CD68E;
    }
    .header{
        height: 40px;background-color: #0c60ee;color: #fff;line-height: 40px;
    }
    .content{
        height: 50px;background-color: #2ac845;color: #333;line-height: 50px;
    }
    .footer{
        height: 60px;background-color: #30BD8A;color: yellow;line-height: 60px;
    }
</style>
<script src="js/vue.js"></script>

</head>
<body>
<div id="myApp">
    <app>
        <app-header></app-header>
        <app-content></app-content>
        <app-footer></app-footer>
    </app>
</div>
</body>
<script src="js/component.js"></script>
</html>
html代码部分没有过多须要解释的,不过要注意的是引用component.js要在Vue.js以及页面渲染完成以后,不然会报错.

最后放上一张效果图

相关文章
相关标签/搜索