Vue.js多重组件嵌套

时间:2023-03-09 08:24:46
Vue.js多重组件嵌套

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>
html代码部分没有过多需要解释的,不过要注意的是引用component.js要在Vue.js以及页面渲染完成之后,否则会报错.

最后放上一张效果图

Vue.js多重组件嵌套