前端流行框架Vue3教程:11. 组件嵌套关系

11. 组件嵌套关系

组件树

组件允许我们将 UI划分为独立的、可重用的部分,并且可以对每个部分进行单独的思考。在实际应用中,组件常常被组织成层层嵌套的树状结构。
这和我们嵌套 HTML 元素的方式类似,Vue 实现了自己的组件模型,使我们可以在每个组件内封装自定义内容与逻辑。

(1)创建组件及引用关系

创建新项目后,我们删掉src/components下的所有文件。并且删除App.vue里的内容。方便我们干净的创建组件和引用关系。

我们在src文件夹下创建个pages文件夹。并创建以下文件:

  • Header.vue

    <script>
    </script>
    <template>
        <h3>Header</h3>
    </template>
    <style scoped>
    /* 需要删掉自带的 main.js里的import './assets/main.css' */
    h3{
        width: 100%;
        height: 100%;
        border:5px solid #999;
        text-align: center;
        line-height: 100px;
        box-sizing: border-box;
    }
    </style>
    
  • App.vue里引入Header

    <script>
    import Header from "./pages/Header.vue"
    export default {
      components: {
        Header
      }
    }
    </script>
    <template>
      <Header />
    
    </template>
    <style>
    </style>
    

    在这里插入图片描述

我们就可以看到页面显示了。

我们继续写其他的:(记得在App.vue里自行引入)

  • Main.vue

    <script>
    export default {
       
    }
    </script>
    <template>
        <div class="main">
            <h3>Main</h3>
        </div>
    
    </template>
    <style scoped>
    .main{
        float: left;
        width: 70%;
        height: 600px;
        border: 5px solid #999;
        box-sizing: border-box;
    }
    </style>
    
  • Aside.vue

    <script>
    export default {
    
    }
    </script>
    <template>
        <div class="aside">
            <h3>Aside</h3>
        </div>
    
    </template>
    <style scoped>
    .aside{
        float: right;
        width: 30%;
        height: 600px;
        border: 5px solid #999;
        box-sizing: border-box;
    }
    </style>
    

    这个时候,我们大概就可以看到页面整体的样式了

    在这里插入图片描述

  • Articke

    <template>
        <h3>Article</h3>
    
    </template>
    <style scoped>
    h3{
        width: 80%;
        margin: 0 auto;
        text-align: center;
        line-height: 100px;
        box-sizing: border-box;
        margin-top: 50px;
        background: #999;
    }
    </style>
    

引用要注意:

上面图我们可以看到,Articke是在Main里的,所以我们要在Main里引用这个组件,而不是App.vue

Main.vue

<script>
import Articke from './Articke.vue';
export default {
   components:{
       Articke
   }
}
</script>
<template>
    <div class="main">
        <h3>Main</h3>
        
        <!-- 因为是2个,所以我们显示2个 -->
        <Articke />
        <Articke />
    </div>
</template>
<style scoped>
....
}
</style>

我们接着写下个组件Item,同样在Aside里要引用三个

Item.vue


<template>
    <h3>Item</h3>

</template>
<style scoped>
h3{
    width: 80%;
    margin: 0 auto;
    text-align: center;
    line-height: 100px;
    box-sizing: border-box;
    margin-top: 10px;
    background: #999;
}
</style>

全部写完后我们看下页面,就完成了

在这里插入图片描述

以上就是组件嵌套关系的介绍和写法。如果同学们自己写一遍的话,就会理解和熟悉。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值