【转】Vue中插槽-----特殊特性slot、slot-scope与指令v-slot的使用方法
1、slot作用/概念:預(yù)先將將來要使用的內(nèi)容進(jìn)行保留;
2、具名插槽:給slot起個(gè)名字
3、slot、slot-scope已經(jīng)被廢棄推薦使用vue2.6.0中的v-slot;但是這邊還是對(duì)新舊方法對(duì)做一下使用說明。
slot插槽(不具名)
<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>
slot具名插槽使用
在組件中使用slot進(jìn)行占位時(shí),在slot標(biāo)簽內(nèi)使用name 屬性給slot插槽定義一個(gè)名字,就是具名插槽。在html中使用具名插槽時(shí),使用slot引入
<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>
<!-- 我們希望把頁頭放這里 -->
<slot name = "header"></slot>//具名插槽
</header>
<section>
主體內(nèi)容部分
</section>
<footer>
<!-- 我們希望把頁腳放這里 -->
<slot name = 'footer'></slot>
</footer>
</div>
</template>
</body>
<script>
Vue.component('Test',{
template:"#test"
});
new Vue({
el:"#app"
})
</script>
作用域插槽:
slot-scope使用:
a、:在組件模板中書寫所需slot插槽,并將當(dāng)前組件的數(shù)據(jù)通過v-bind綁定在slot標(biāo)簽上。
b、:在組件使用時(shí),通過slot-scope=“gain”,接收組件中slot標(biāo)簽上綁定的數(shù)據(jù)。
c、:通過gain.xxx就可以使用綁定數(shù)據(jù)了
<body>
<div id="app">
<Test>
<div slot="default" slot-scope="gain">//作用域插槽的用法(slot-scope)
{{ gain.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="gain">//v-slot定義作用域插槽
<div>
<h3>slot</h3>
<p> {{gain.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)大家要注意。
總結(jié)
以上是生活随笔為你收集整理的【转】Vue中插槽-----特殊特性slot、slot-scope与指令v-slot的使用方法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: import java.io 包下载_G
- 下一篇: 开源网络安全检测工具——伏羲 Fuxi-