1.插槽的概念:
插槽是子組件給父組件提供的占位符,用<slot></slot>來表示本缠,父組件可以在這個占位符中填充任何模板代碼,如 HTML、組件等器仗,填充的內(nèi)容會替換子組件的<slot></slot>標簽
匿名插槽
代碼如下:
HelloWorld為子組件
父組件如下:
當我們沒給子組件定義插槽時,父組件里面的‘123’童番,無法在瀏覽器顯示出來如下圖所示:
當我們給子組件定義一個插槽時
父組件里面的123就會在瀏覽器里面顯示出來
插槽使用 - 具名插槽:
<!DOCTYPE html>
<html lang="en">
<head>
? ? <meta charset="UTF-8">
? ? <meta name="viewport" content="width=device-width, initial-scale=1.0">
? ? <title>Document</title>
<body>
? ? <div id="app">
? ? ? ? <base-layout>
? ? ? ? ? ? <!-- 2精钮、 通過 slot 屬性來指定, 這個 slot 的值必須和下面 slot 組件的 name 值對應(yīng)上,如果沒有匹配到 則放到匿名的插槽中? -->
? ? ? ? ? ? <p slot='header'>標題信息</p>
? ? ? ? ? ? <p>主要內(nèi)容1</p>4
? ? ? ? ? ? <p>主要內(nèi)容2</p>
? ? ? ? ? ? <p slot='footer'>底部信息信息</p>
? ? ? ? </base-layout>
? ? ? ? <base-layout>
? ? ? ? ? ? <!-- 注意點:template臨時的包裹標簽最終不會渲染到頁面上? ? -->
? ? ? ? ? ? <!-- <template slot='header'> -->
? ? ? ? ? ? <template v-slot:header>
? ? ? ? ? ? ? ? <p>標題信息1</p>
? ? ? ? ? ? ? ? <p>標題信息2</p>
? ? ? ? ? ? </template>
? ? ? ? ? ? <p>主要內(nèi)容1</p>
? ? ? ? ? ? <p>主要內(nèi)容2</p>
? ? ? ? ? ? <template slot='footer'>
? ? ? ? ? ? ? ? <p>底部信息信息1</p>
? ? ? ? ? ? ? ? <p>底部信息信息2</p>
? ? ? ? ? ? </template>
? ? ? ? </base-layout>
? ? </div>
? ? <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
? ? <script>
? ? ? ? // 1剃斧、使用 <slot> 中的 "name" 屬性綁定元素 指定當前插槽的名字
? ? ? ? Vue.component('base-layout', {
? ? ? ? ? ? template: `
? ? ? ? ? ? ? ? <div>
? ? ? ? ? ? ? ? ? ? <header>
? ? ? ? ? ? ? ? ? ? ? ? <slot name='header'></slot>
? ? ? ? ? ? ? ? ? ? </header>
? ? ? ? ? ? ? ? ? ? <main>
? ? ? ? ? ? ? ? ? ? ? ? <slot></slot>
? ? ? ? ? ? ? ? ? ? </main>
? ? ? ? ? ? ? ? ? ? <footer>
? ? ? ? ? ? ? ? ? ? ? ? <slot name='footer'></slot>
? ? ? ? ? ? ? ? ? ? </footer>
? ? ? ? ? ? ? ? </div>
? ? ? ? ? ? `
? ? ? ? });
? ? ? ? const vm = new Vue({
? ? ? ? ? ? el: '#app',
? ? ? ? });
? ? </script>
</body>
</html>
作用域插槽
- 父組件對子組件加工處理
- 既可以復(fù)用子組件的 slot轨香,又可以使 slot 內(nèi)容不一致
原理:通過在子組件的<slot></slot>來自定義屬性向父組件傳值,父組件通過<template slot-scope='接受數(shù)據(jù)'></template>
來實現(xiàn)對子組件的數(shù)據(jù)進行加工