默认插槽
1.在Category中创建插槽
<slot>默认值<slot/>
2.在App中使用
<Category tittle="美食"> <ul ><li v-for="(l,index) in foods" :key="index">{{l}}</li></ul> </Category>
3.运行后的效果
4.不在app中使用插槽的效果
具名插槽,具名之意,就是给插槽附名
1.定义
<slot name="games">游戏</slot> <slot name="foods">食物</slot>
2.使用
<div class="container"><Category tittle="美食"><ul slot="foods"><li v-for="(l, index) in games" :key="index">{{ l }}</li></ul></Category><Category tittle="游戏"><template slot="games"><ul><li v-for="(l, index) in games" :key="index">{{ l }}</li></ul></template></Category></div>
3.运行,因为我们写了两个插槽,另一个没有被使用就展示的默认值
作用域插槽(将数据放到子组件中)
1.子组件
<template><div class="category"><h2>{{tittle}}分类</h2><slot name="game" :shiwu="games">游戏</slot><slot name="food" :youxi="foods">食物</slot> </div> </template><script> export default {name:"Category",props:['tittle'],data() {return {foods: ["香蕉", "苹果", "橙子", "梨", "火锅"],games: ["王者", "崩铁", "原神", "火影"],} } } </script><style scoped> .category{background-color: skyblue;width: 200px;height: 300px; } h2{text-align: center;background-color: orange; } ul li{display: flex;justify-content: start; } </style>
2.App组件
<template><div class="container"><Category tittle="游戏"><template slot="game" slot-scope="g"> <ul ><li v-for="(l, index) in g.shiwu" :key="index">{{ l }}</li></ul></template></Category><Category tittle="食物"><template slot="food" slot-scope="f" > <ul><li v-for="(l, index) in f.youxi" :key="index">{{ l }}</li></ul></template></Category></div> </template><script> import Category from "./components/Category"; export default {name: "App",components: { Category }, } </script><style scoped> .container {display: flex;justify-content: space-around; } </style>
3.运行效果