网站首页 > 知识剖析 正文
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>
全部写完后我们看下页面,就完成了
以上就是组件嵌套关系的介绍和写法。如果同学们自己写一遍的话,就会理解和熟悉。
猜你喜欢
- 2025-02-04 真的不考虑下grid布局?它有多方便你知道嘛?
- 2025-02-04 超详细!10分钟开发一个Vue3的后台管理系统
- 2025-02-04 精通 CSS 选择器(二)(css选择器知识点总结)
- 2025-02-04 后台开发必备:每个程序员都应掌握的缓存技术
- 2025-02-04 【开源】基于 Vue 和 Gin 开发的前后端分离的开源框架
- 2025-02-04 Go + Amis 快速搭建建议动态网站(自己搭建动态域名服务器)
- 2025-02-04 Java开发人员必须重视HTML5的5点理由
- 2025-02-04 前端又出新框架了,你还学得动吗?
- 2025-02-04 秒杀系统实战(四)| 缓存与数据库双写一致性实战
- 2025-02-04 别再问了,数据库与缓存一致性问题今天全整齐活了
- 最近发表
- 标签列表
-
- xml (46)
- css animation (57)
- array_slice (60)
- htmlspecialchars (54)
- position: absolute (54)
- datediff函数 (47)
- array_pop (49)
- jsmap (52)
- toggleclass (43)
- console.time (63)
- .sql (41)
- ahref (40)
- js json.parse (59)
- html复选框 (60)
- css 透明 (44)
- css 颜色 (47)
- php replace (41)
- css nth-child (48)
- min-height (40)
- xml schema (44)
- css 最后一个元素 (46)
- location.origin (44)
- table border (49)
- html tr (40)
- video controls (49)