vue中作用域插槽
- 理解:
- 数据在组件的自身
![在这里插入图片描述](https://img-blog.csdnimg.cn/86a3e4f91be14787a714c8979572b6c9.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA5p6X5LmLLg==,size_20,color_FFFFFF,t_70,g_se,x_16)
- 但根据数据生成的结构需要组件的使用者来决定:
![在这里插入图片描述](https://img-blog.csdnimg.cn/055a1785728b4d10883b97241a1649e9.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA5p6X5LmLLg==,size_20,color_FFFFFF,t_70,g_se,x_16)
- 代码:
- Category.vue(子组件中)
<template>
<div class="category">
<h3>{{ title }}分类</h3>
<!-- 定义一个默认插槽,那么App.vue中相应的组件标签里标签体的内容会往这个插槽中放置 -->
<slot :game="games"></slot>
</div>
</template>
<script >
export default {
name: "Category",
props: ["title"],
data() {
return {
games: ["红警在线", "穿越火线", "劲舞团"],
};
},
};
</script>
<style scoped>
.category {
background-color: skyblue;
width: 200px;
height: 300px;
}
h3 {
text-align: center;
background-color: orange;
}
</style>
<template>
<div class="container">
<Category title="游戏">
<!-- 要用作用域插槽属性,那么真正被传入插槽结构的外侧必须被template曝光 -->
<template scope="asd">
<!-- 这个asd就是被传过来的Category.vue中games那个数组,然而games数组在APP.vue中叫game -->
<!-- 其中scope也可以被写成slot-scope,后者这个写法是vue2最新写法 -->
<ul>
<li v-for="(g, index) in asd.game" :key="index">
{{ g }}
</li>
</ul>
</template>
</Category>
</div>
</template>
<script>
import Category from "./components/Category";
export default {
name: "App",
components: { Category },
};
</script>
<style>
.container,
.foot,
.dianyin {
display: flex;
justify-content: space-around;
}
</style>