《Vue.js实战》学习笔记 slot

2020-04-29  本文已影响0人  863cda997e42

Vue.js实战

props 传递数据,events 触发事件和 slot 内容分发构成了 Vue 组件的3个API来源,再复杂的组件也是由这3部分构成的。

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>slot 用法</title>
    <script src="https://unpkg.com/vue/dist/vue.min.js"></script>

</head>

<body>
    <div id="app">
        <child-component>
            <p>分发的内容</p>
            <p>更多分发的内容</p>
        </child-component>
    </div>
    <script>
        Vue.component("child-component", {
            template: '\
            <div>\
                <slot>\
                    <p>如果父组件没有插入内容,我将作为默认出现</p>\
                </slot>\
            <div>',
        });

        var app = new Vue({
            el: "#app",
        });
    </script>

</body>

</html>

具名 Slot

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>具名 Slot</title>
    <script src="https://unpkg.com/vue/dist/vue.min.js"></script>

</head>

<body>
    <div id="app">
        <child-component>
            <h2 slot="header">标题</h2>
            <p>正文的内容</p>
            <p>更多正文的内容</p>
            <div solt="footer">底部信息</div>
        </child-component>
    </div>
    <script>
        Vue.component("child-component", {
            template: '\
            <div class="container">\
                <div class="header">\
                    <slot name="header"></slot>\
                </div>\
                <div class="main">\
                    <slot></slot>\
                </div>\
                <div class="footer">\
                    <slot name="footer"></slot>\
                </div>\
            <div>',
        });

        var app = new Vue({
            el: "#app",
        });
    </script>

</body>

</html>

作用域插槽

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>作用域插槽</title>
    <script src="https://unpkg.com/vue/dist/vue.min.js"></script>

</head>

<body>
    <div id="app">
        <child-component>
            <template slot-scope="props">
                <p>来自父组件的内容</p>
                <p>{{props.msg}}</p>
            </template>
        </child-component>
    </div>
    <script>
        Vue.component("child-component", {
            template: '\
            <div class="container">\
               <slot msg="来自子组件的内容"></slot>\
            <div>',
        });

        var app = new Vue({
            el: "#app",
        });
    </script>
</body>

</html>
上一篇下一篇

猜你喜欢

热点阅读