卡槽
具名卡槽: 同时有多个卡槽 为每个卡槽指定名字即可
作用域卡槽: 如何在父组件中使用子组件的数据来自定义插槽内容,简单理解:子中插槽默认展示自己内部的数据,但是父想对这个数据做一下拼接展示,那么问题来了,父子是不同的作用域,父如何拿到子的数据呢,作用域插槽就是为了解决这个问题
2.6 之前已废弃的语法
具名卡槽
- 子组件: 为 slot 指定名字
html
<div class="container">
<header>
<slot name="header"></slot>
</header>
<main>
<slot></slot>
</main>
<footer>
<slot name="footer"></slot>
</footer>
</div>
- 父组件 通过 slot 对应
html
<base-layout>
<template slot="header">
<h1>Here might be a page title</h1>
</template>
<p>A paragraph for the main content.</p>
<p>And another one.</p>
<template slot="footer">
<p>Here's some contact info</p>
</template>
</base-layout>
作用域卡槽
有的时候卡槽里面的子组件想给父组件传值
- 子组件
html
<template>
<div>
<slot name="kaocaoa" :data="dataA"></slot>
<slot name="kaocaob" :data="dataB"></slot>
</div>
</template>
<script>
export default {
data() {
return {
message: "子组件",
dataA: "dataA里面的数据",
dataB: "dataB里面的数据",
};
},
};
</script>
<style lang="less" scoped></style>
- 父组件
html
<template>
<div>
<header></header>
{{ message }}
<Chacaoa>
<div class="sloata" slot="kaocaoa" slot-scope="shuju1">
<p>{{ shuju1.data }}</p>
</div>
<div class="sloatb" slot="kaocaob" slot-scope="shuju2">
<p>{{ shuju2.data }}</p>
</div>
</Chacaoa>
</div>
</template>
<script>
import Header from "@/components/common/Header";
import Chacaoa from "@/components/common/Sloata";
export default {
data() {
return {
message: "首页",
};
},
components: {
Header,
Chacaoa,
},
};
</script>
<style lang="less" scoped>
.sloata {
width: 300px;
height: 100px;
background: blue;
color: yellow;
}
.sloatb {
width: 300px;
height: 100px;
background: red;
color: black;
}
</style>
2.6 之后的新语法
引入了 v-slot
具名卡槽
- 父组件(必须绑定在 template 上)
html
<base-layout>
<template v-slot:header>
<h1>Here might be a page title</h1>
</template>
<p>A paragraph for the main content.</p>
<p>And another one.</p>
<template v-slot:footer>
<p>Here's some contact info</p>
</template>
</base-layout>
- 子组件
html
<div class="container">
<header>
<slot name="header"></slot>
</header>
<main>
<slot></slot>
</main>
<footer>
<slot name="footer"></slot>
</footer>
</div>
作用域卡槽
子组件要给父组件传值
- 子组件
html
<template>
<div>
<slot name="kaocaoa" :data="dataA"></slot>
<slot name="kaocaob" :data="dataB"></slot>
</div>
</template>
<script>
export default {
data() {
return {
message: "子组件",
dataA: "dataA里面的数据",
dataB: "dataB里面的数据",
};
},
};
</script>
<style lang="less" scoped></style>
- 父组件
html
<current-user>
<template v-slot:default="slotProps">
<!-- 在这里不可以的直接使用user,因为父级组件无法识别user -->
{{ slotProps.user.firstName }}
</template>
</current-user>