用法见官方文档深入组件章节,插槽部分:
参考文档:插槽-作用域插槽-插槽prop
有时让插槽内容能够访问子组件中才有的数据是很有用的。
需求:插槽内容能够访问子组件中才有的数据
TodoList.vue
<template>
<div v-for="(todoItem, index) in state.todoList">
<slot :item="todoItem" :index="index"></slot>
</div>
</template>
<script setup>
import { reactive } from '@vue/reactivity'
const state = reactive({
todoList: ['Feed a cat', 'Buy milk']
})
</script>
<style lang="less">
</style>
item
和 index
;useSlot.vue
<template>
<div>
<todo-list>
<template v-slot:default="slotProps">
<button @click="handleClick(slotProps)">{{slotProps.item}}</button>
</template>
</todo-list>
<div>
<h3>点击按钮</h3>
<li>{{`${state.slotProps.index + 1}: ${state.slotProps.item}`}}</li>
</div>
</div>
</template>
<script setup>
import { reactive } from '@vue/reactivity'
import TodoList from './TodoList.vue'
const state = reactive({
slotProps: {
index: 0,
item: 'default'
}
})
const handleClick = (slotProps) => {
state.slotProps = slotProps
}
</script>
<style lang="less">
</style>