初步了解插槽
示例
<template>
<div>
// 這個(gè)組件中沒(méi)有任何內(nèi)容,所以在插槽里面就默認(rèn)用了插槽里的默認(rèn)值监婶,也就是Submit,結(jié)果圖1
<navigation-link />
// 這個(gè)組建中有了內(nèi)容齿桃,所以會(huì)替代插槽中的默認(rèn)內(nèi)容Submit,結(jié)果圖2
<navigation-link>
Save
</navigation-link>
</div>
</template>
<script>
import Vue from 'vue'
// 下面的slot就是插槽了煮盼,如果在slot標(biāo)簽里寫(xiě)內(nèi)容則是代表了插槽里的默認(rèn)值短纵,也就是Submit
Vue.component('navigation-link', {
template: `<button type="submit">
<slot>Submit</slot>
</button>`,
});
export default {
name: 'HelloWorld',
components: [
'navigation-link'
],
data() {
return {
}
},
}
</script>
結(jié)果
圖1
圖2
具名插槽
思考
<div class="container">
<header>
<!--我們想把頭部放到這里-->
</header>
<main>
<!--我們想把主要內(nèi)容放到這里-->
</main>
<footer>
<!--我們想把頁(yè)腳放到這里-->
</footer>
</div>
解決
// 如下准潭,我們只是在slot標(biāo)簽內(nèi)加了個(gè)name="..."忠售,這樣就制定了插槽的名字
Vue.component('navigation-link', {
template: `<div class="container">
<header>
// 這是個(gè)具名插槽
<slot name="header"></slot>
</header>
<main>
// 這是個(gè)默認(rèn)插槽
<slot></slot>
</main>
<footer>
// 這是個(gè)具名插槽
<slot name="footer"></slot>
</footer>
</div>`,
});
使用
<template>
<navigation-link>
// v-slot:名字雀监,也就是具名插槽name="名字"中的名字
<template v-slot:header>
<h3>這是頁(yè)面標(biāo)題</h3>
</template>
// 如果插槽是默認(rèn)值這里也可以不寫(xiě) v-slot:default
<template v-slot:default>
<p>這是頁(yè)面內(nèi)容</p>
</template>
<template v-slot:footer>
<h3>這是頁(yè)腳</h3>
</template>
</navigation-link>
</template>
// 當(dāng)然你也可以這么寫(xiě),這個(gè)寫(xiě)法和上面的等價(jià)
<template>
<navigation-link>
// 對(duì)于v-slot:名字我們也可以寫(xiě)成 #名字 效果是一樣的
<template #header>
<h3>這是頁(yè)面標(biāo)題</h3>
</template>
// 如果插槽是默認(rèn)值這里就可以寫(xiě)成#default
<template #default>
<p>這是頁(yè)面內(nèi)容</p>
</template>
<template #footer>
<h3>這是頁(yè)腳</h3>
</template>
</navigation-link>
</template>
結(jié)果
圖3
作用域插槽
示例
<script>
import Vue from 'vue'
Vue.component('current-user', {
template: `<div class="container">
<span>
<slot :user="user">{{user.lastName}}</slot>
</span>
</div>`,
data() {
return {
user: {
firstName:'彥宏',
lastName:'李'
}
}
},
});
......
</script>
使用
// 這里定義了個(gè)props碱蒙,這個(gè)名字你可以隨便起断部,#default="slotProps"...都可以
<current-user #default="props">
{{props.user.firstName}}
</current-user>
結(jié)果
圖4
解構(gòu)插槽
有了ES6的解構(gòu)賦值淘捡,我們相應(yīng)的也會(huì)有解構(gòu)插槽站叼,這個(gè)比上面的作用域要靈活一些例诀,結(jié)果和上個(gè)作用域插槽的一樣哦 推薦3湟住梗脾!
// 這個(gè)解構(gòu)的是:user="user", 如果是:kitty="user"那么就應(yīng)該寫(xiě)#default="kitty"
<current-user #default="{user}">
{{user.firstName}}
</current-user>