在開發(fā)項(xiàng)目的過程中插槽的使用是不可避免地,而且在View、Element-ui這些框架中都會(huì)有插槽的影子,今天就來(lái)說(shuō)說(shuō)插槽的使用。
<div id="app">
<navigation-link url="/profile">
Your Profile
</navigation-link>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
Vue.component('navigation-link',{
props: {
url: String
},
template: `<a v-bind:href="url"
class="nav-link">
<slot></slot>
</a>`
});
new Vue({
el: '#app'
})
</script>
這也就是插槽最簡(jiǎn)單的使用方法啦,插槽內(nèi)可以包含任何模板代碼,包括組件。

image.png
這里引用vue官網(wǎng)上的一句話,也就是說(shuō)如果上述代碼中的navigation-link這個(gè)組件中不包含<slot>元素,則組件標(biāo)簽中的內(nèi)容Your Profile將不會(huì)被渲染。
具名插槽
<div id="app">
<navigation-link v-slot="header" url="/profile">
Your Profile
</navigation-link>
<base-layout>
<template v-slot:header>
<h2>我是導(dǎo)航</h2>
</template>
<template v-slot:default>
<h2>我是內(nèi)容</h2>
</template>
<template v-slot:footer>
<h2>我是底部</h2>
</template>
</base-layout>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
Vue.component('navigation-link',{
props: {
url: String
},
template: `<a v-bind:href="url"
class="nav-link">
<slot></slot>
</a>`
});
const baseLayout = {
template: `<div class="container">
<header><slot name="header"></slot></header>
<main><slot></slot></main>
<footer><slot name="footer"></slot></footer>
</div>`
};
new Vue({
el: '#app',
components: {
'base-layout': baseLayout
}
})
</script>
跟著文檔走一遍,具名插槽只會(huì)渲染通過v-slot綁定的組件,沒有定義name的插槽默認(rèn)為default
作用域插槽
還是引入官方的例子
<div id="app">
<current-user>
<template v-slot:default="slotProps">
{{slotProps.user.firstName}}
</template>
</current-user>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
const currentUser = {
data() {
return {
user: {
firstName: 'chen',
lastName: 'jx'
}
}
},
template: `<div>
<span>
<slot v-bind:user="user">{{user.lastName}}</slot>
</span>
</div>`
}
new Vue({
el: '#app',
components: {
'base-layout': baseLayout,
'current-user': currentUser
}
})
</script>
插槽的主要用法就是這些,還有一些就是插槽的縮寫語(yǔ)法,這些官方都解釋的很清楚,就不在舉例子啦!