在Vue中使用插槽 插槽和具名插槽/作用域插槽

版权声明: https://blog.csdn.net/xyphf/article/details/83690782

在Vue中使用插槽
插槽和具名插槽

<body>
    <div id="app">
        <child content="<p>123</p>">
            <h1>Dell</h1>
        </child>

        <div>------------------</div>

        <body-content>
            <div class='header' slot='header'>
                header
            </div>
           <div class='footer' slot='footer'>
               footer
           </div>
        </body-content>
    </div> 
    
    <script>
        Vue.component('child',{
            props:['content'],
            template: `<div>
                            <p>hello</p>
                            <div v-html="this.content"></div>
                            <slot>default content</slot>
                       </div>`
        })

        // vue中的具名插槽
        Vue.component('body-content',{
            // 多行字符串语法
            template: `<div>
                            <slot name='header'>
                                <div>default header</div>
                            </slot>
                            <div class='content'>content</div>
                            <slot name='footer'></slot>
                       </div>`
        })

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

作用域插槽
固定写法

<body>
    <div id="app">
        <child>
            <template slot-scope="props">
                <li>{{props.item}}</li>
            </template>
        </child>
    </div>
    
    <script>
        Vue.component('child',{
            data: function(){
                return {
                    list: [1,2,3,4]
                }
            },
            template:`<div>
                        <ul>
                            <slot v-for="item of list" :item=item>
                            </slot>
                        </ul>
                      </div>`
        })
        var vm = new Vue({
            el: "#app"
        })
    </script>
</body>

猜你喜欢

转载自blog.csdn.net/xyphf/article/details/83690782