Vue 内容分发slot

1、概述

内容分发:混合父组件的内容与子组件自己的模板。

2、单个插槽

当子组件模板只有一个没有属性的插槽时,父组件传入的整个内容片段将插入到插槽所在的 DOM 位置,并替换掉插槽标签本身。

最初在 <slot> 标签中的任何内容都被视为备用内容。备用内容在子组件的作用域内编译,并且只有在宿主元素为空,且没有要插入的内容时才显示备用内容。

<!DOCTYPE html>
<html lang="zh">

    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <title>vue 内容分发 slot</title>
    </head>

    <body>
        <div id="root">
            <div>
                <h1>我是父组件的标题</h1>
                <my-component>
                    <p>这是一些初始内容</p>
                    <p>这是更多的初始内容</p>
                </my-component>
            </div>
        </div>
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

        <script type="text/javascript">
            Vue.component('my-component', {
                template: `<div>
                  <h2>我是子组件的标题</h2>
                  <slot>
                    只有在没有要分发的内容时才会显示。
                  </slot>
                  <h2>子组件结束</h2>
                </div>`,
                data: function() {
                    return {

                    }
                }
            })

            new Vue({
                el: '#root',
                data: {
                    messages: ''
                }
            })
        </script>
    </body>

</html>

3、具名和匿名混合

<!DOCTYPE html>
<html lang="zh">

    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <title>vue 内容分发 slot</title>
    </head>

    <body>
        <div id="root">
            <app-layout>
                <h1 slot="header">这里可能是一个页面标题</h1>

                <p>主要内容的一个段落。</p>
                <p>另一个主要段落。</p>

                <p slot="footer">这里有一些联系信息</p>
            </app-layout>
        </div>
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

        <script type="text/javascript">
            Vue.component('app-layout', {
                template: `<div class="container">
                  <header>
                    <slot name="header"></slot>
                  </header>
                  <main>
                    <slot></slot>
                  </main>
                  <footer>
                    <slot name="footer"></slot>
                  </footer>
                </div>`,
                data: function() {
                    return {

                    }
                }
            })

            new Vue({
                el: '#root',
                data: {
                    messages: ''
                }
            })
        </script>
    </body>

</html>

猜你喜欢

转载自www.cnblogs.com/mengfangui/p/8932542.html