领先的免费Web技术教程,涵盖HTML到ASP.NET

网站首页 > 知识剖析 正文

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

nixiaole 2025-02-04 15:27:56 知识剖析 12 ℃

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>

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

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

Tags:

最近发表
标签列表