作用
让父组件可以向子组件指定位置插入html结构,也是一种组件间通信的方式,适用于父组件===>子组件。
分类
默认插槽、具名插槽、作用域插槽
使用方式:
默认插槽
父组件
<Catogary title="苹果"><img src="./assets/logo.png" /></Catogary> <Catogary title="香蕉"> <ul> <li>123</li> <li>456</li> <li>789</li> </ul> </Catogary>
子组件
<template> <div> <div>{{ title }}</div> <slot>插槽默认内容</slot> </div> </template> <script> export default { name: "Catogary", props: ["title"], } </script>
具名插槽
父组件
<Catogary> <img slot="pic" src="./assets/logo.png" /> <template v-slot:name>或 <template slot="name"> <ul> <li>这是一个li</li> <li>这是一个li</li> <li>这是一个li</li> </ul> </template> </Catogary>
子组件
<template> <div> <div>{{ title }}</div> <slot name="pic">这是图片具名插槽</slot> <slot name="name">这是名称具名插槽</slot> </div> </template>
作用域插槽
- 理解:数据在组件的自身,但根据数据生成的结构需要组件的使用者来决定。
- 具体编码
App.vue
<template> <div id="app"> <Catogary> <template scope="{dataList}"> <ul><li v-for="item in dataList" :key="item.id">{{ item.name }}</li></ul> </template> </Catogary> <Catogary> <template scope="{dataList}"> <ol><li v-for="item in dataList" :key="item.id">{{ item.name }}</li></ol> </template> </Catogary> </div> </template>
Catogary.vue
<template> <div><slot :dataList="dataList"></slot></div> </template> <script> export default { name: "Catogary", data() { return { dataList: [ { id: "001", name: "标题一" }, { id: "002", name: "标题二" }, { id: "003", name: "标题三" }, { id: "004", name: "标题四" }, ], }; }, }; </script>