遇到問題
今天我在網(wǎng)上做vue開源項目的時候發(fā)現(xiàn),如果要做多頁面,樣式該咋辦?難道每個都一個一個插入嗎?這樣重復就是罪過,萬一需求改變每個都改該多麻煩!
所以我看了vue官方文檔,發(fā)現(xiàn)有一個slot功能
eg
<template>
<div class="nav-wrapper">
<div class="content">
111
</div>
<Nav/>
</div>
</template>
<script lang="ts">
import Vue from "vue";
export default Vue.extend({
name:'money'
});
</script>
<style lang="scss" scoped>
.nav-wrapper {
border: 1px black solid;
display: flex;
flex-direction: column;
height: 100vh;
}
.content {
overflow: auto;
border: 1px solid blue;
flex-grow: 1;
}
</style>
這是一個頁面的vue文件,如果每個頁面樣式相似都要寫這么多真的浪費時間而且不符合美觀
所以我想到把重復的內(nèi)容封裝到一個component里面,我暫且命名為Layout
//Layout.vue
<template>
<div class="nav-wrapper">
<div class="content">
</div>
<Nav/>
</div>
</template>
<script lang="ts">
import Vue from "vue";
export default Vue.extend({
name:'Layout'
});
</script>
<style lang="scss" scoped>
.nav-wrapper {
border: 1px black solid;
display: flex;
flex-direction: column;
height: 100vh;
}
.content {
overflow: auto;
border: 1px solid blue;
flex-grow: 1;
}
</style>
而刪除了這些重復內(nèi)容,原本的vue就變得干凈清爽多了
<template>
<p>
111
</p>
</template>
<script lang="ts">
import Vue from "vue";
export default Vue.extend({
name:'money'
});
</script>
接下來把Layout組件在全局引用后,我們遇到一個問題,如何把這個111的p標簽引入到Layout組件中呢
通過不斷翻閱Vue文檔,找到一個方法,也就是這次的主角slot
slot
slot他只有一個屬性就是
name - string,是用于命名插槽。
它的用法就是
<slot> 元素作為組件模板之中的內(nèi)容分發(fā)插槽。<slot> 元素自身將被替換。
//Layout.vue
<template>
<div class="nav-wrapper">
<div class="content">
<slot></slot>
</div>
<Nav/>
</div>
</template>
這樣就會把外面?zhèn)鬟M來的把slot標簽代替
但是這種方法是不夠全面,而且Vue文檔也說已經(jīng)廢棄但是沒有移除,那咋樣才能跟好呢?因為無法針對性的插入,比如遇到不同頁面樣式不同就沒轍了
所以我們可以采用V-slot標簽
v-slot
預(yù)期:可放置在函數(shù)參數(shù)位置的 JavaScript 表達式 (在支持的環(huán)境下可使用解構(gòu))??蛇x,即只需要在為插槽傳入 prop 的時候使用。
參數(shù):插槽名 (可選,默認值是
default)-
限用于
<template>- 組件 (對于一個單獨的帶 prop 的默認插槽)
-
用法:
提供具名插槽或需要接收 prop 的插槽。
-
示例:
<!-- 具名插槽 --> <base-layout> <template v-slot:header> Header content </template> Default slot content <template v-slot:footer> Footer content </template> </base-layout> <!-- 接收 prop 的具名插槽 --> <infinite-scroll> <template v-slot:item="slotProps"> <div class="item"> {{ slotProps.item.text }} </div> </template> </infinite-scroll> <!-- 接收 prop 的默認插槽,使用了解構(gòu) --> <mouse-position v-slot="{ x, y }"> Mouse position: {{ x }}, {{ y }} </mouse-position>
跟 v-on 和 v-bind 一樣,v-slot 也有縮寫,即把參數(shù)之前的所有內(nèi)容 (v-slot:) 替換為字符 #。例如 v-slot:header 可以被重寫為 #header:
<base-layout>
<template #header>
<h1>Here might be a page title</h1>
</template>
<p>A paragraph for the main content.</p>
<p>And another one.</p>
<template #footer>
<p>Here's some contact info</p>
</template>
</base-layout>
然而,和其它指令一樣,該縮寫只在其有參數(shù)的時候才可用。這意味著以下語法是無效的:
<!-- 這樣會觸發(fā)一個警告 -->
<current-user #="{ user }">
{{ user.firstName }}
</current-user>
如果你希望使用縮寫的話,你必須始終以明確插槽名取而代之:
<current-user #default="{ user }">
{{ user.firstName }}
</current-user>