一.插槽是個什么玩意,能吃嗎
- 在vue中【插槽】,從字面意思來看,插槽意味著【內容的增加】,回到vue的使用場景,插槽就是【父組件呼叫子組件時,額外增加的內容】,
- 插槽顯不顯示、顯示的內容是由父組件來控制的,而插槽在哪里顯示由子組件來決定
二.插槽怎么用,好用嗎
1.默認插槽
父組件
1 <template> 2 <div> 3 父組件的內容 4 <slot1> 5 <p style="color:red">父組件中插槽內容</p> 6 </slot1> 7 </div> 8 </template>
子組件
<template>
<div>
<div>slot1子組件</div>
<slot></slot>
</div>
</template>
<script>
效果

從上面可以看出,父組件參考子組件標簽里的內容被加在了子組件<slot>標簽中,slot就是一個插槽,當父組件呼叫子組件時,父組件的內容被插入到子組件相應的位置中了,
2.具名插槽
顧名思義,就是有具體名字的插槽,子組件中與父組件相對應名字的內容將添加,
3.作用域插槽
父組件
<template> <div> 作用域插槽父組件 <slot2> <template slot-scope="user"> <div v-for="(item, index) in user.data" :key="index"> <span>姓名:{{item.name}}</span>; <span>年齡:{{item.age}}</span> </div> </template> </slot2> </div> </template> <script> import slot2 from "./slot2" export default { name: 'main', components: { slot2 } } </script> <style scoped> </style>
子組件
<template> <div> 作用域插槽的子組件 <slot :data="https://www.cnblogs.com/robinw666/p/user"></slot> </div> </template> <script> export default { name: 'slot2', data () { return { user: [ {name: '王五', age: '23'}, {name: '李二', age: '45'}, {name: '張三', age: '15'} ] } } } </script>
效果

父組件使用slot-scope接收來自子組件傳過來的引數,
使用場景:如果子組件中的某一部分的資料,每個父組件都會有自己的一套對該資料的不同的呈現方式,這時就需要用到作用域插槽
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/164087.html
標籤:JavaScript
上一篇:JS---BOM基本知識 (頂級物件,系統對話框,加載事件,location物件, history物件, navigator物件)
下一篇:JavaScript按鈕排他思想
