Vue插槽
插槽
作用
让父组件可以向子组件指定位置插入html
结构,也是一种组件间通信的方式,适用于父组件 => 子组件
。
分类
- 默认插槽
- 具名插槽
- 作用域插槽
使用方法
默认插槽
//父组件中
<Category>
<div>html结构</div>
</Category>
//子组件中
<template>
<div>
<!-- 定义一个插槽 -->
<slot>我是默认值,当使用者没有传递具体结构时,我会出现</slot>
</div>
</template>
具名插槽
//父组件
<Category>
<div slot="center">html结构</div>
<!-- v-slot只能用在template标签 -->
<!-- template可以包裹多层html结构,且不生成真实DOM元素,可以省一层结构 -->
<template v-slot:footer>
<div>html结构</div>
<h4>html结构</h4>
</template>
</Category>
//子组件
<template>
<div>
<slot name="center"></slot>
<slot name="footer"></slot>
</div>
</template>
作用域插槽
- 理解:数据在组件的自身,但根据数据生成的结构需要组件的使用者来决定(games数据在Categoty组件中,但用哪种html结构展示数据由App组件决定)。
//父组件
<Category>
<template v-slot="{games}">
//生成的是ol有序列表
<ol>
<li v-for="(item, index) in games" :key="index">{{ item }}</li>
</ol>
</template>
</Category>
<Category>
<template v-slot="{games}">
//生成的是h4标题
<h4 v-for="(item, index) in games" :key="index">{{ item }}</h4>
</template>
</Category>
//子组件
<template>
<div>
<slot :games="games"></slot>
</div>
</template>
...
//数据在Category自身
<script>
...
data() {
return {
games: ['红色警戒', '穿越火线', '劲舞团'],
}
},
}
...
</script>
ps:这两种写法都弃用了。
<template slot-scope="{games}"></template>
<template scope="{games}"></template>
现在用
<template v-slot="{games}"></template>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步