-
作用:让父组件可以向子组件指定位置插入html结构,也是一种组件间通信的方式,适用于父组件===>子组件。
-
分类:默认插槽、具名插槽、作用域插槽
一、默认插槽
父组件中使用了多个相同的子组件,
若想只在foods所在子组件中放入其他结构,以下就麻烦了。
<template>
<div class="container">
<Category :listData="foods" />
<Category :listData="games" />
<Category :listData="films" />
</div>
</template>
<script>
import Category from "@/components/Category";
export default {
name: "TianyvUseCategory",
components: { Category },
data() {
return {
foods: ["a", "b", "c"],
games: ["aaa", "bbb", "ccc"],
films: ["a11", "b22", "c33"],
};
},
</script>
Category.vue
<template>
<div class="category">
<h3>分类</h3>
<ul>
<li v-for="(item, index) in listData" :key="index">{{ item }}</li>
</ul>
</div>
</template>
<script>
export default {
name: 'Category',
props: ['listData']
......
</script>
可以用插槽解决:
<template>
<div class="container">
<h2>我的Home的内容</h2>
<Category>
<h3>我是插槽内容哇</h3>
</Category>
<Category>
<ul>
<li v-for="(item, index) in games" :key="index">{{ item }}</li>
</ul>
</Category>
<Category>
<ul>
<li v-for="(item, index) in films" :key="index">{{ item }}</li>
</ul>
</Category>
</div>
</template>
<script>
import Category from "../components/Category.vue";
export default {
name: "Home",
components: { Category },
data() {
return {
games: ["aaa", "bbb", "ccc"],
films: ["a11", "b22", "c33"],
};
},
......
</script>
Category.vue
<template>
<div class="category">
<h3>分类</h3>
<!-- 定义插槽 -->
<slot>
<h5>这里可以设置插槽默认值</h5>
</slot>
</div>
</template>
二、具名插槽
<Category>
<!-- slot属性指定插槽名,可以设置本标签放入哪个插槽中 -->
<h3 slot="cen">我是插槽内容哇</h3>
<!-- 在 2.6.0 中,为具名插槽和作用域插槽引入了一个新的统一的语法 (即 v-slot 指令)。
它取代了 slot 和 slot-scope
v-slot只能使用在template标签上-->
<template v-slot:foo>
<div>
哈哈哈哈哈哈哈哈哈哈哈哈
</div>
</template>
</Category>
Category.vue
<template>
<div class="category">
<h3>分类</h3>
<!-- 具名插槽 -->
<slot name="cen"></slot>
<slot name="foo"></slot>
</div>
</template>
三、作用域插槽
当数据在子组件中,但是父组件中,所用数据一样,但插入结构不一样,要拿到子组件的数据,就用到了作用域插槽。
<Category>
<!-- 必须被template包裹,才能拿到Category中插槽传来的值
值赋给了scope (写scope或slot-scope都可)-->
<template scope="a">
<ul>
<li v-for="(item, index) in a.aaa" :key="index">{{ item }}</li>
</ul>
</template>
</Category>
<Category>
<template scope="a">
<h4 v-for="(item, index) in a.aaa" :key="index">{{ item }}</h4>
</template>
</Category>
Category.vue
<!-- 给使用本组件插槽的组件传值 -->
<slot :aaa="aaa"></slot>
</div>
</template>
<script>
export default {
name: "Category",
data() {
return {
aaa: ['红色', '蓝色', '绿色']
};
},
......
</script>