vue插槽 slot
Vue 實(shí)現(xiàn)了一套內(nèi)容分發(fā)的 API,這套 API 的設(shè)計(jì)靈感源自 Web Components 規(guī)范草案,將 <slot> 元素作為承載分發(fā)內(nèi)容的出口。
vue文檔
子組件:
<template>
<div>
<h1>我是seo組件</h1>
<!-- header -->
<slot name="header" :row='obj'>
</slot>
<!-- middle 匿名插槽-->
<slot >
</slot>
<!-- footer -->
<slot name="footer" :row='obj'>
</slot>
</div>
</template>
<script>
export default {
data(){
return{
obj:{
header:"頭部?jī)?nèi)容",
footer:"尾部?jī)?nèi)容"
}
}
}
}
</script>
slot中name屬性和父組件中v-slot:后面跟的參數(shù)一致,則會(huì)讓父組件中的template內(nèi)容在這展示。即通過具名來判斷,父組件的內(nèi)容分發(fā)到那一塊。
由于組件之間作用域是獨(dú)立的,如果想在父組件中用到子組件的數(shù)據(jù),則需要用到作用域插槽。
自 2.6.0 起有所更新。已廢棄的使用 slot-scope attribute 的語法。但是依舊可以使用,直到Vue3.0中廢棄。
作用域插槽使用就是在子組件中用屬性綁定在 具名插槽的元素上,然后在父組件中v-slot:(插槽的名字)='scope',scope是自己寫的獲取的變量,可以自行定義。
父組件:
<template>
<div class="about">
<h1>This is an about page</h1>
<seo>
<!-- footer -->
<template v-slot:footer="scope">
<h1>footer</h1>
<div>
{{scope.row.footer}}
</div>
</template>
<!-- header -->
<template v-slot:header='scope'>
<h1>title</h1>
<div>
{{scope.row.header}}
</div>
</template>
<!-- middle 非具名插槽都會(huì)顯示在匿名插槽中-->
<div>
我是在父組件中的插槽middle
</div>
<h1>123</h1>
</seo>
</div>
</template>
<script>
import seo from "../components/seo"
export default {
components:{
seo,
},
data(){
return{
}
}
}
</script>
在子組件中定義好位置以后,父組件中內(nèi)容分發(fā),是無所謂位置的。比如我這header部分和footer部分就不是對(duì)應(yīng)位置。
展示效果

預(yù)覽.png
接著我們就可以在父組件中修改子組件的分發(fā)上來的數(shù)據(jù)了。
<template>
<div class="about">
<h1>This is an about page</h1>
<seo>
<template v-slot:footer="scope">
<h1>footer</h1>
<div>
<el-select v-model="scope.row.footer">
<el-option v-for="item in footer_list" :key="item.id" :label="item.name" :value="item.id">
</el-option>
</el-select>
{{scope.row.footer}}
</div>
</template>
<template v-slot:header='scope'>
<h1>title</h1>
<div>
{{scope.row.header}}
</div>
</template>
<div>
我是在父組件中的插槽middle
</div>
<h1>123</h1>
</seo>
</div>
</template>
<script>
import seo from "../components/seo"
export default {
components:{
seo,
},
data(){
return{
footer_list:[
{id:1,name:'1底部43'},
{id:2,name:'2底部93'},
]
}
}
}
</script>

預(yù)覽2.png
當(dāng)我選擇下拉選擇‘1底部43’

預(yù)覽3.png