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以及頁面渲染完成以後,不然會報錯.

最後放上一張效果圖

相關文章
相關標籤/搜索