组件1的代码,带有slot-scope特性
@/components/slot-test/slot-test.vue
<template>
<view>
<slot></slot>
<slot name="test"></slot>
<view v-for="(item, index) in list" :key="index">
<slot name="item" :item="item" :index="index"></slot>
</view>
</view>
</template>
<script>
export default {
name: 'slot-test',
props: {
list: {
type: Array,
default () {
return []
}
}
}
}
</script>
<style>
</style>
组件2的代码,纯粹只是一个容器
@/components/slot-test/another-slot.vue
<template>
<view>
<slot></slot>
</view>
</template>
<script>
</script>
<style>
</style>
测试页面的代码
<template>
<view>
<view style="margin: 20px;">下面是暴露在外部的自定义组件</view>
<slot-test v-if="asyncList" :list="syncList">
<view style="background-color: red; margin: 20px;" @click="defaultClickHandler">点我检查默认插槽的点击事件</view>
<template v-slot:test>
<view style="background-color: green; margin: 20px;" @click="nameClickHandler">点我检查具名插槽的点击事件,下面是带有slot-scope的具名插槽,点击可以检查事件</view>
</template>
<template v-slot:item="{ item, index }">
<view style="background-color: yellow; margin: 20px;" @click="clickHandler(item, index)">
<view>slot-scope传来数据 {{ item.txt }}</view>
<view>slot-scope传来索引 {{ index }}</view>
<view>同步数据 {{ syncList[index].txt }}</view>
<view>异步数据 {{ asyncList[index].txt }}</view>
</view>
</template>
</slot-test>
<view style="margin: 20px;">下面是嵌套在自定义组件内部的自定义组件</view>
<another-slot>
<slot-test v-if="asyncList" :list="syncList">
<view style="background-color: red; margin: 20px;" @click="defaultClickHandler">点我检查默认插槽的点击事件</view>
<template v-slot:test>
<view style="background-color: green; margin: 20px;" @click="nameClickHandler">点我检查具名插槽的点击事件,下面是带有slot-scope的具名插槽,点击可以检查事件</view>
</template>
<template v-slot:item="{ item, index }">
<view style="background-color: yellow; margin: 20px;" @click="clickHandler(item, index)">
<view>slot-scope传来数据 {{ item.txt }}</view>
<view>slot-scope传来索引 {{ index }}</view>
<view>同步数据 {{ syncList[index].txt }}</view>
<view>异步数据 {{ asyncList[index].txt }}</view>
</view>
</template>
</slot-test>
</another-slot>
</view>
</template>
<script>
import slotTest from '@/components/slot-test/slot-test.vue'
import anotherSlot from '@/components/slot-test/another-slot.vue'
export default {
name: 'slotBug',
components: {
slotTest,
anotherSlot
},
data () {
return {
syncList: [
{ txt: '1' },
{ txt: '2' },
{ txt: '3' }
],
asyncList: null
}
},
methods: {
clickHandler (item, index) {
console.log('来自默认插槽传来的数据', item.txt)
console.log('插槽的索引值', index)
console.log('索引值调用同步数据', this.syncList[index].txt)
console.log('索引值调用异步数据', this.asyncList[index].txt)
},
defaultClickHandler () {
console.log('默认插槽')
},
nameClickHandler () {
console.log('具名插槽')
}
},
created () {
setTimeout(() => {
this.asyncList = [
{ txt: '11111111' },
{ txt: '22222222' },
{ txt: '33333333' }
]
}, 3000)
}
}
</script>
<style>
</style>