09: vue3 组件嵌套关系

组件嵌套关系

组件允许我们将 UI 划分为独立的、可重用的部分,并且可以对每个部分进行单独的思考。在实际应用中,组件常常被组织成层层嵌套的树状结构:

这和我们嵌套 HTML 元素的方式类似,Vue 实现了自己的组件模型,使我们可以在每个组件内封装自定义内容与逻辑。

创建组件及引用关系

项目中新建pages文件夹,然后添加如下组件

Header.vue

 1 <template>
 2     <h3>Header</h3>
 3 </template>
 4 
 5 <style scoped>
 6     h3{
 7         width:100%;
 8         height: 100px;
 9         border: 5px solid #999;
10         text-align: center;
11         line-height: 100px;
12         box-sizing: border-box;
13     }
14 </style>

Main.vue

 1 <template>
 2     <div class="main">
 3         <h3>Main</h3>
 4         <Article></Article>
 5         <Article></Article>
 6     </div>
 7     
 8 </template>
 9 
10 <script>
11 import Article from './Article.vue';
12 export default{
13     components:{
14         Article
15     }
16 }
17 </script>
18 <style scoped>
19 .main{
20     float: left;
21     width: 70%;
22    
23     height: 400px;
24     border: 5px solid #999;
25     box-sizing: border-box;
26 }
27 </style>

Aside.vue 

 1 <template>
 2     <div class="aside">
 3         <h3>Aside</h3>
 4         <Item></Item>
 5         <Item></Item>
 6         <Item></Item>
 7     </div>
 8 </template>
 9 <script>
10 import Item from './Item.vue';
11 
12 export default{
13     components:{
14         Item
15     }
16 }
17 </script>
18 <style scoped>
19 .aside{
20     float: right;
21     width:29%;
22     height: 400px;
23     border: 5px solid #999;
24     box-sizing: border-box;
25     
26 }
27 </style>

Article.vue

 1 <template>
 2     <h3>Article</h3>
 3 </template>
 4 <style scoped>
 5 h3{
 6     width:80%;
 7     margin:0 auto;
 8     text-align: center;
 9     line-height: 100px;
10     box-sizing: border-box;
11     margin-top: 50px;
12     background: #999;
13 }
14 </style>

Item.vue

 1 <template>
 2     <h3>Item</h3>
 3 </template>
 4 <style scoped>
 5 h3{
 6     width:80%;
 7     margin:0 auto;
 8     text-align: center;
 9     line-height: 100px;
10     box-sizing: border-box;
11     margin-top: 10px;
12     background: #999;
13 }
14 </style>

App.vue

 1 <template>
 2 
 3 <!-- 第三步:显示组件 -->
 4 <Header></Header>
 5 <Main></Main>
 6 <Aside></Aside>
 7 </template>
 8 
 9 <script>
10 //第一步:引入组件
11 import Header from "./pages/Header.vue";
12 import Main from "./pages/Main.vue";
13 import Aside from "./pages/Aside.vue";
14 
15 //第二步:注入组件
16 export default{
17   components:{
18     Header,
19     Main,
20     Aside
21   }
22 }
23 
24 </script>

 

posted on 2023-07-05 15:03  wuzx-blog  阅读(755)  评论(0编辑  收藏  举报