使用場景
如開發一個組件,裏面一些子元素希望是有調用着來定義,可以使用slot
一:沒有slot
<child>沒有插槽slot我不展示</child>
Vue.component('child',{
template:`<div>child</div>`
})
結果:
註釋:在父組件中調用子組件時給子組件添加插槽內容,如果子組件裏不包含<slot></slot>元素,則添加的插槽內容會被拋棄
二:默認插槽
<child1></child1>
<child1>我是默認插槽</child1>
<child1>{{parentMsg}}</child1>
Vue.component('child1',{
template:`<div>child1<slot>哈哈哈哈</slot></div>`
})
結果:
註釋:
- 沒有設置子組件插槽內容,則會顯示子組件<slot></slot>中的內容
- 設置了子組件插槽內容,則插槽內容會替代<slot></slot>中的內容
- 子組件插槽內容是在父組件調用時設置,默認的作用域是父組件,因此可以訪問父組件的值,這點個人認為類似父組件給子組件傳值props,但是props主要傳遞值,插槽可以傳遞DOM
三:具名插槽
<child2>
<template slot="aaa">
我是aaa具名插槽
</template>
<template slot="bbb">
我是bbb具名插槽
</template>
<!-- V2.6.0之後的寫法縮寫 -->
<template #ccc>
我是ccc具名插槽
</template>
</child2>
Vue.component('child2',{
template:`<div>child2
<slot name='aaa'></slot>
<slot name='bbb'></slot>
<slot name='ccc'></slot>
</div>`
})
四:作用域插槽
<child3>
<!-- V2.6.0之前的寫法 -->
<template slot-scope="scope">
{{scope}}
</template>
</child3>
Vue.component('child3',{
template:`<div>child3
<slot :msg="msg" text="哈哈哈"></slot>
</div>`,
data(){
return{
msg:"子組件的參數"
}
}
})
結果:
<child4 >
<!-- V2.6.0之後的寫法 -->
<template v-slot="msg">
<li>{{msg.msg.name}}{{msg.msg.age}}歲</li>
</template>
</child4>
Vue.component('child4',{
template:`<div>child4
<ul>
<slot v-for="item in childMsg" :msg=item></slot>
</ul>
</div>`,
data(){
return{
childMsg:[
{
name:"張三",
age:18
},
{
name:"李四",
age:19
}
]
}
}
})
結果:
註釋:
作用域插槽與普通插槽區別:[作用域插槽]父組件插槽的內容能訪問子組件傳的數據[普通插槽]則不行
源碼地址: https://github.com/shangliaoy...