组件化开发--组件的嵌套关系与插槽在子组件中的使用
1、设置Parent与Child两个子组件,在申明组件的时候Parent在根组件中申明,而Child在Parent组件中申明,他们的关系就变为:
Parent组件是根组件的子组件,Child组件是Parent组件的子组件
2、data数据在Parent中如何使用
let Parent = {
template: '#parent',
data: function () {
return {
title: '活着',
descriptions: '讲述了在大时代背景下,随着内战、三反五反,大跃进,文化大革命等社会变革,徐福贵的人生和家庭不断经受着苦难,到了最后所有亲人都先后离他而去,仅剩下年老的他和一头老牛相依为命。',
price: '¥56'
}
},
components: {
Child
}
}
(1)因为Child是在Parent中申明的,所以Child可以使用Parent中data的数据,子组件的data数据必须要用function return函数包裹,不然无法被读取到:
子组件:
// 子组件
let Child = {
template: '#child'
}
let Parent = {
template: '#parent',
data: function () {
return {
title: '活着',
descriptions: '讲述了在大时代背景下,随着内战、三反五反,大跃进,文化大革命等社会变革,徐福贵的人生和家庭不断经受着苦难,到了最后所有亲人都先后离他而去,仅剩下年老的他和一头老牛相依为命。',
price: '¥56'
}
},
components: {
Child
}
}
父组件:
let vm = new Vue({
el: '#app',
data: {},
components: {
Parent
}
})
视图层父组件:
<!-- 父组件 -->
<div id="app">
<parent></parent>
<child>
<h1 slot="t">{{title}}</h1>
<h2 slot="des">{{descriptions}}</h2>
<h3 slot="p">{{price}}</h3>
</child>
</div
视图层子组件:
<!-- 子组件 -->
<template id="parent">
<div>
<p>parent组件</p>
<child>
<h1 slot="t">{{title}}</h1>
<h2 slot="des">{{descriptions}}</h2>
<h3 slot="p">{{price}}</h3>
</child>
</div>
</template> <template id="child">
<div>
<p>child组件</p>
<div class="title">
<slot name="t">此处显示标题内容</slot>
</div>
<div class="descriptions">
<slot name="des">此处显示简介内容</slot>
</div>
<div class="price">
<slot name="p">此处显示价格</slot>
</div>
</div>
</template>
.title {
text-align: center;
color: aquamarine;
font-size: 30px;
}
.descriptions {
color: burlywood;
font-size: 26px;
}
.price {
text-align: right;
font-size: 24px;
color: coral;
}
代码演示:
(2)虽然Child已经在Praent中申明了,但在根组件中还是可以申明,不过不能像上面的Child组件一样去使用Parent的data数据,只能使用根组件中的data数据:
let vm = new Vue({
el: '#app',
data: {
title: '小王',
descriptions: '两眼泪汪汪',
price: '¥23'
},
components: {
Parent,
Child
}
})
<div id="app">
<parent></parent>
<child>
<h1 slot="t">{{title}}</h1>
<h2 slot="des">{{descriptions}}</h2>
<h3 slot="p">{{price}}</h3>
</child>
</div>
<template id="child">
<div>
<p>child组件</p>
<div class="title">
<slot name="t">此处显示标题内容</slot>
</div>
<div class="descriptions">
<slot name="des">此处显示简介内容</slot>
</div>
<div class="price">
<slot name="p">此处显示价格</slot>
</div>
</div>
</template>
代码演示:
评论
匿名评论
隐私政策
你无需删除空行,直接评论以获取最佳展示效果