Vue.js多重組件嵌套
Vue.js中提供了非常棒的組件化思想,組件提高了代碼的復用性.今天我們來實現一個形如
<app>
<app-header></app-header>
<app-content></app-content>
<app-footer></app-footer>
</app>
的一個復合組件
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>