26_插槽
01_默认插槽
App.vue
<template>
<div class="container">
<Category title="美食" >
<img src="https://s3.ax1x.com/2021/01/16/srJlq0.jpg" alt="" />
</Category>
<Category title="游戏" >
<ul>
<li v-for="(item, index) in games" :key="index">
{{ item }}
</li>
</ul>
</Category>
<Category title="电影">
<video controls src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"></video>
</Category>
</div>
</template>
<script>
import Category from "./components/Category";
export default {
name: "App",
components: {
Category,
},
data() {
return {
foods: ["火锅", "火锅", "火锅", "火锅"],
games: ["王者", "王者", "王者", "王者"],
films: ["<奇迹笨小孩>", "<奇迹笨小孩>", "<奇迹笨小孩>", "<奇迹笨小孩>"],
};
},
};
</script>
<style>
.container {
display: flex;
justify-content: space-around;
}
video{
width: 100%;
}
</style>
Category.vue
<template>
<div class="category">
<h3>{{ title }}分类</h3>
<!-- 定义一个插槽 等着使用者进行填充 -->
<slot></slot>
<!-- <slot>我是一些默认值,没有传递具体结构时,我会出现</slot> -->
</div>
</template>
<script>
export default {
name: "Category",
props: ["title"],
};
</script>
<style>
.category {
background-color: skyblue;
width: 200px;
height: 300px;
}
h3 {
text-align: center;
background-color: orange;
}
img{
width: 100%;
}
</style>
02_具名插槽
App.vue
<template>
<div class="container">
<Category title="美食">
<img
slot="center"
src="https://s3.ax1x.com/2021/01/16/srJlq0.jpg"
alt=""
/>
<a slot="footer" href="https://www.baidu.com">去百度</a>
</Category>
<Category title="游戏">
<ul slot="center">
<li v-for="(item, index) in games" :key="index">
{{ item }}
</li>
</ul>
<div slot="footer">
<a href="https://www.baidu.com">去百度</a>
<a href="https://www.baidu.com">去百度</a>
</div>
</Category>
<Category title="电影">
<video
slot="center"
controls
src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"
></video>
<template v-slot:footer>
<a href="https://www.baidu.com">去百度</a>
<a href="https://www.baidu.com">去百度</a>
<a href="https://www.baidu.com">去百度</a>
<h4 style="text-align:center">前去观影</h4>
</template>
</Category>
</div>
</template>
Category.vue
<template>
<div class="category">
<h3>{{ title }}分类</h3>
<slot name="center"></slot>
<slot name="footer"></slot>
</div>
</template>
03_作用域插槽
数据在Category.vue,但 App.vue要用
App.vue
<template>
<div class="container">
<Category title="游戏">
<template scope="atguigu">
<ul>
<li v-for="(item, index) in atguigu.games" :key="index">
{{ item }}
</li>
</ul>
</template>
</Category>
<Category title="游戏">
<template scope="{games}">
<ol>
<li v-for="(item, index) in games" :key="index">
{{ item }}
</li>
</ol>
</template>
</Category>
<Category title="游戏">
<template slot-scope="atguigu">
<h4>
<li v-for="(item, index) in atguigu.games" :key="index">
{{ item }}
</li>
</h4>
</template>
</Category>
</div>
</template>
Category.vue
<template>
<div class="category">
<h3>{{ title }}分类</h3>
<slot :games="games">我是默认的一些内容</slot>
</div>
</template>
<script>
export default {
name: "Category",
props: ["title"],
data() {
return {
games: ["王者", "王者", "王者", "王者"],
};
},
};
</script>