作用:增強組件的可擴展性 ,擴展組件的時候不傷害源代碼
插槽<slot></solt>寫在子組件中,起到占位的作用
父組件中:<template></template>使用插槽 ,給空的插槽重新給數(shù)據(jù)進行渲染
分類 :
1. 匿名插槽
2. 具名插槽 -- 有兩種語法
(1)2.6.0之前
在子組件中:
<slot name="mingzi"></slot>
在父組件中:
<div slot="mingzi"></div>
(2)新推薦的語法
在子組件中:
<slot name="mingzi1"></slot>
<slot name="mingzi2"></slot>
在父組件里面寫:
<子組件名>
v-slot是個指令 沒有名字默認(rèn)為v-slot:default
<template v-slot:mingzi1>
<div>第一個插槽</div>
</template>
可以簡寫為#
<template #mingzi2>
<p>第二個插槽</p>
</template>
</子組件名>
子組件向父組件傳值:
2.6.0之后傳值
在子組件template中:
<slot name="mingzi1" :n="n"></slot>
script中:
data(){
return {
n:123456
}
}
在父組件中:
<template v-slot:mingzi1="{n}">{{n}}</template>
這樣就能夠?qū)崿F(xiàn)從子組件向父組件傳值了。嘻嘻嘻
2.6.0之前傳值 基本已經(jīng)廢棄
在子組件template中:
<slot name="mingzi2" :s="s"></slot>
script中:
data(){
return {
s:"gggggg"
}
}
在父組件中:
<div slot="mingzi2" slot-scope="{s}">{{s}}</div>
父組件調(diào)用子組件的方法或數(shù)據(jù):
給子組件一個ref標(biāo)識
父組件:this.$refs.ref標(biāo)識.數(shù)據(jù)或方法
子組件調(diào)用父組件的方法或數(shù)據(jù):
this.$parent.數(shù)據(jù)或方法