插槽
插槽我對他的理解就是父組件的東西插到子組件的<slot></slot>裏面,也不知道這樣理解對不對,方便自己記憶
普通插槽
父組件如下:
<template>
<div class="father">
<h3>這裏是父組件</h3>
<child>
<div>
<span>這是父組件插到子組件的slot標籤</span>
<span>這是父組件插到子組件的slot標籤</span>
<span>這是父組件插到子組件的slot標籤</span>
</div>
</child>
</div>
</template>
<script>
import child from './children'
export default {
components: {
child
}
}
</script>
子組件如下:
<template>
<div>
<h3>這裏是子組件,父組件的child將會插到slot標籤裏面</h3>
<slot></slot>
</div>
</template>
<script>
export default {
}
</script>
顯示效果如下:
具名插槽
父組件
<template>
<div class="father">
<h3>這裏是父組件</h3>
<child>
<div>
<p>這不是具名插槽</p>
<p>這不是具名插槽</p>
<p>這不是具名插槽</p>
</div>
<div slot="havename">
<p>這是具名插槽</p>
<p>這是具名插槽</p>
<p>這是具名插槽</p>
</div>
</child>
</div>
</template>
<script>
import child from './children'
export default {
components: {
child
}
}
</script>
子組件
<template>
<div>
<h3>這裏是子組件,父組件的child將會查到下面</h3>
<slot name="havename"></slot>
<slot></slot>
</div>
</template>
<script>
export default {
}
</script>
效果如下:
作用域插槽
我對他的理解就是數據在子組件裏面,父組件可以用
父組件
<template>
<div class="father">
<h3>這裏是父組件</h3>
<child>
<div>
<p>這不是具名插槽</p>
<p>這不是具名插槽</p>
<p>這不是具名插槽</p>
</div>
<div slot="havename">
<p>這是具名插槽</p>
<p>這是具名插槽</p>
<p>這是具名插槽</p>
</div>
<template slot-scope="fromchildData">
<p v-for="(item,index) of fromchildData.data" :key="index">{{item}}</p>
</template>
</child>
</div>
</template>
<script>
import child from './children'
export default {
components: {
child
}
}
</script>
子組件
<template>
<div>
<h3>這裏是子組件,父組件的child將會查到下面</h3>
<slot name="havename"></slot>
<slot></slot>
<slot :data="childData"></slot>
</div>
</template>
<script>
export default {
data() {
return {
childData:[1,2,3,4,5]
}
},
}
</script>
效果如下: