父組件中引用支持插槽內容的子組件,形如如下(假設子組件爲NavigationLink.vue
)css
<navigation-link url="/profile"> Your Profile </navigation-link>
而後在子組件<template>
模板中使用<slot></slot>
,形如如下:html
<a v-bind:href="url" class="nav-link" > <slot></slot> </a>
這樣之後,當組件渲染的時候,子組件中的<slot></slot>
將會被替換爲父組件模板中,子組件起始標籤和結束標籤之間的內容--這裏稱之爲「插槽內容」。vue
插槽內能夠包含任何模板代碼,包括 HTML:ide
<navigation-link url="/profile"> <!-- 添加一個 Font Awesome 圖標 --> <span class="fa fa-user"></span> Your Profile </navigation-link>
甚至其它的組件:測試
<navigation-link url="/profile"> <!-- 添加一個圖標的組件 --> <font-awesome-icon name="user"></font-awesome-icon> Your Profile </navigation-link>
若是子組件 template
中沒有包含一個 <slot>
元素,則父組件中,該組件起始標籤和結束標籤之間的任何內容都會被拋棄flex
自定義卡片組件,用於展現不一樣的內容,形式爲 顯示卡片標題和內容,卡片和卡片之間看起來須要有「分界條」ui
Testpage.vue
<template> <div class="page-main"> <div class="main-content"> <card class="authors-single" title="測試標籤1"> <div style="height:50px;width:60px">hello</div> </card> <card class="authors-single" title="測試標籤2"> <div>卡片內容</div> </card> </div> </div> </template> <script> import Card from "@/components/Card"; export default { components: { Card }, }; </script> <style scoped lang="scss"> .page-main { height: calc(100vh - 129px); padding: 10px 10px; display: flex; flex-direction: column; .main-content { overflow: auto; flex: auto; } } </style>
Card.vue
組件路徑位於@/components/Card/Card.vue
url
<template> <div class="card"> <div class="card-title">{{title}}</div> <div class="card-content"> <slot></slot> </div> </div> </template> <script> export default { props: { title: { type: String } } } </script> <style lang="scss" scoped> .card { display: flex; flex-direction: column; padding: 2px 5px; &-title { flex: none; padding: 0.4em 8px; font-size: 17px; position: relative; background-color: #f8f8f8; &::before { content: ""; width: 4px; height: 100%; background: #59bcc7; position: absolute; top: 0; left: 0; } } &-content { flex: auto; padding: 10px; margin-top: 10px; background-color: #f8f8f8; } } </style>