作用域插槽:可從子組件獲取數(shù)據(jù)的可復(fù)用的插槽
作用域是子組件本身綁定的數(shù)據(jù)
場(chǎng)景:典型代表性 - 列表組件 【child 組件做列表的循環(huán)(ul),列表中的每一項(xiàng)如何顯示并不關(guān)心,顯示由外部決定,外部組件調(diào)用chlid,需要向子組件傳遞slot(li),告知子組件如何顯示列表的每一項(xiàng)】【既可以復(fù)用子組件的slot,又可以使slot內(nèi)容不一致】
// child.vue
<template>
<!-- <div v-for="user in users"> ... </div> -->
<ul>
<slot v-for="user in users" :user="user" name="user"></slot>
</ul>
</template>
<script>
export default {
props: {
users: { // 也可內(nèi)部data自定義
type: Array,
default () { return []}
}
}
}
</script>
// father.vue
<template>
<child :users="users">
<template slot="user" slot-scopr="slotProps">
<li>name: {{ slotProps.user.name }} & age: {{ slotProps.user.age}}</li>
</template>
</child>
</template>
<script>
export default {
data() {
return {
users: [ {name: 'tom', age: '20'}]
}
}
</script>