插槽内容在父作用域渲染,默认看不到子组件数据。
子组件在 slot 标签上绑定属性,把数据抛出去。
父组件用 v-slot 解构,值就传进来了。
具名插槽写成 #名字="{ 字段 }" 的形式。
别在父模板里直接访问子组件的 data 或方法。
<!-- 子组件 ChildCard.vue:把数据绑到 slot 上 -->
<template>
<div class="card">
<slot :item="item" :index="index" :toggle="toggle" />
<slot name="footer" :item="item" />
</div>
</template>
<!-- 父组件:默认插槽 -->
<ChildCard v-slot="{ item, index, toggle }">
<span>{{ index }} - {{ item.name }}</span>
<button @click="toggle">切换</button>
</ChildCard>
<!-- 父组件:具名插槽 -->
<ChildCard>
<template #footer="{ item }">
<button @click="item.save()">保存</button>
</template>
</ChildCard>
THE END






暂无评论内容