Vue - 具名插槽和作用域插槽

2019-11-04  本文已影响0人  ElricTang

slot(插槽)可以理解为占位符

一. 具名插槽(使用新的v-slot语法)

    <body>
        <div id='app'>
            <base-layout>
                <template v-slot:header>
                    <h1>标题</h1>
                </template>
                <template v-slot:default>
                    <p>A paragraph for the main content.</p>
                    <p>And another one.</p>
                </template>
                <template v-slot:footer>
                    <p>结尾</p>
                </template>
            </base-layout>
        </div>
        <script>
            var baseLayout = {
                template:`<div class="container">
                        <header>
                            <slot name="header"></slot>
                        </header>
                        <main>
                            <slot></slot>
                        </main>
                        <footer>
                            <slot name="footer"></slot>
                        </footer>
                        </div>`
            }
            var vm = new Vue({
                el:'#app',
                components:{
                    'base-layout':baseLayout
                }
            })
        </script>
    </body>

注意点:
1. 子组件模板内使用<slot name="header"></slot>设置一个占位的插槽

<div class="container">
     <header>
          <slot name="header"></slot>
     </header>
     <main>
          <slot></slot>
     </main>
     <footer>
          <slot name="footer"></slot>
     </footer>
</div>

2. 父组件内使用<template v-slot:header></template>替换占位内容

<base-layout>
    <template v-slot:header>
        <h1>标题</h1>
    </template>
    <template v-slot:default>
        <p>A paragraph for the main content.</p>
        <p>And another one.</p>
    </template>
    <template v-slot:footer>
        <p>结尾</p>
    </template>
</base-layout>

二. 作用域插槽(使用2,6.0新语法,slot-scope已废弃)

    <body>
        <div id='app'>
            <child>
                <template v-slot:header="slotProps">
                    <p>{{slotProps.title}}</p>
                    <p>{{slotProps.summary}}</p>
                </template>
            </child>
        </div>
        <script>
            var child = {
                template:`<div>
                     <header>
                       <slot name="header" :title="title" :summary="summary"></slot>
                     </header>
                 </div>`,
                data(){
                    return {
                        title:'hello world',
                        summary:'学习作用域插槽'
                    }
                }
            }
            var vm = new Vue({
                el:'#app',
                components:{
                    child
                }
            })
        </script>
    </body>
效果
注意点 解析
上一篇下一篇

猜你喜欢

热点阅读