Vue.js中提供了很是棒的組件化思想,組件提升了代碼的複用性.今天咱們來實現一個形如html
<app> <app-header></app-header> <app-content></app-content> <app-footer></app-footer> </app>
的一個複合組件vue
(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' }); })()
//js代碼 Vue.component('app-header',{ template:'#headerTemplate' }); //html代碼 <template id="headerTemplate"> <div class="header" slot="header">this is header</div> </template>
<!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>