Vue插槽

插槽

插槽語法是Vue實現的組件內容分發,當組件嵌套時,能夠靈活定義組件內容。插槽分爲三種:匿名插槽,具名插槽,做用域插槽。vue

1. 匿名插槽

示例代碼以下:bash

// index.vue
<Child>
    <!-- 匿名插槽 -->
    <template>我是匿名插槽的內容......</template>
</Child>
複製代碼
// child.vue
<!-- 匿名插槽 -->
<slot></slot>
複製代碼

2. 具名插槽

子組件slot標籤上掛載name屬性,指定插槽的名稱。示例代碼以下:markdown

// index.vue
<Child>
    <!-- 具名插槽 -->
    <template v-slot:header>我是具名插槽header裏的內容......</template>
</Child>
複製代碼
// child.vue
<!-- 具名插槽 -->
<slot name="header"></slot>
複製代碼

3. 做用域插槽

使用做用域插槽,能夠將子組件裏的數據經過插槽做用域的形式在組件嵌套中使用。示例代碼以下:spa

// index.vue
<Child>
    <!-- 做用域插槽 -->
    <template v-slot:footer="context">我是具名插槽footer裏的內容,拿到了子組件做用域插槽的數據:{{context.title}}-{{context.content}};同時也獲取到父組件的數據:{{title}}</template>
</Child>
複製代碼
// child.vue
<!-- 做用域插槽 -->
<slot name="footer" :title="title" :content="content"></slot>
複製代碼
相關文章
相關標籤/搜索