不具名插槽
<body>
<div id="app">
<Test>
<div>slot插槽占位內(nèi)容</div>
</Test>
</div>
<template id="test">
<div>
<slot></slot>//定義插槽
<h3>這里是test組件</h3>
</div>
</template>
</body>
<script>
Vue.component('Test',{
template:"#test"
});
new Vue({
el:"#app",
})
</script>
具名插槽
<body>
<div id="app">
<Test>
<div slot="header">這里是頭部</div>//具名插槽使用
<div slot="footer">這里是尾部</div>
</Test>
</div>
<template id="test">
<div>
<slot name="header"></slot>//具名插槽
<h3>這里是Test組件</h3>
<slot name="footer"></slot>
</div>
</template>
</body>
<script>
Vue.component(
'Test',{
template:"#test"
});
new Vue({
el:"#app"
})
</script>
v-slot
v-slot在組件中使用slot進(jìn)行占位時(shí)蜈彼,也是在slot標(biāo)簽內(nèi)使用name 屬性給slot插槽定義一個(gè)名字。但是在html內(nèi)使用時(shí)就有些不同了俺驶。需要使用template模板標(biāo)簽幸逆,template標(biāo)簽內(nèi),使用v-slot指令綁定插槽名暮现,標(biāo)簽內(nèi)寫入需要添加的內(nèi)容还绘。
<body>
<div id="app">
<Test>
<template v-slot:header>//v-slot指令使用插槽
<h2>slot頭部?jī)?nèi)容</h2>
</template>
<p>直接插入組件的內(nèi)容</p>
<template v-slot:footer>
<h2>slot尾部?jī)?nèi)容</h2>
</template>
</Test>
</div>
<template id ='test'>
<div class="container">
<header>
<!-- 我們希望把頁(yè)頭放這里 -->
<slot name = "header"></slot>//具名插槽
</header>
<section>
主體內(nèi)容部分
</section>
<footer>
<!-- 我們希望把頁(yè)腳放這里 -->
<slot name = 'footer'></slot>
</footer>
</div>
</template>
</body>
<script>
Vue.component('Test',{
template:"#test"
});
new Vue({
el:"#app"
})
</script>
作用域插槽:
slot-scope使用:
在組件模板中書寫所需slot插槽,并將當(dāng)前組件的數(shù)據(jù)通過(guò)v-bind綁定在slot標(biāo)簽上栖袋。
在組件使用時(shí)拍顷,通過(guò)slot-scope=“scope”,接收組件中slot標(biāo)簽上綁定的數(shù)據(jù)。
通過(guò)scope.xxx就可以使用綁定數(shù)據(jù)了
<body>
<div id="app">
<Test>
<div slot="default" slot-scope="scope">//作用域插槽的用法(slot-scope)
{{ scope.msg }}
</div>
</Test>
</div>
<template id="test">
<div>
<slot name="default" :msg="msg"> </slot>
<p>這里是test組件</p>
</div>
</template>
</body>
<script>
new Vue({
el:"#app",
components:{
'Test':{
template:"#test",
data(){
return {
msg:"你好"
}
},
}
}
})
</script>
作用域插槽:v-slot的用法
<body>
<div id="app">
<Test>
<template v-slot:header="scope">//v-slot定義作用域插槽
<div>
<h3>slot</h3>
<p> {{scope.msg}} </p>
</div>
</template>
</Test>
</div>
<template id="test">
<div>
<slot name="header":msg="msg"></slot>
<p>這里是test組件</p>
</div>
</template>
</body>
<script>
Vue.component('Test',{
template:"#test",
data(){
return {
msg:'這里是頭部'
}
}
});
new Vue({
}).$mount("#app")
</script>
Vue2.6.0中使用v-slot指令取代了特殊特性slot與slot-scope塘幅,但是從上述案例可以看出昔案,v-slot在使用時(shí),需要在template標(biāo)簽內(nèi)电媳,這點(diǎn)大家在應(yīng)用時(shí)要注意踏揣。
轉(zhuǎn)載自:https://blog.csdn.net/sunhuaqiang1/article/details/106742853
參考:https://blog.csdn.net/u012733501/article/details/107046903/
參考:https://www.cnblogs.com/bulici/p/11733840.html