Vue插槽 slot

1. 什么是插槽

  插槽slot 是往父组件中插入额外内容,实现组件的复用,一个插槽插入到一个对应的标签中

2. 实例:

  一个组件中不允许有两个匿名插槽

</head>
<body>
    <div id="root">
        <child>
            <div class="header" slot="header">header</div>
            <div class="footer" slot="footer">footer</div>
            hello     <!-- 没有名字的标签默认会放置到name:default的slot中 -->
        </child>
    </div>
<script>
    Vue.component('child',{
        template: `<div>
                        <slot name="header"></slot>   <!--  有名插槽 -->
                        <div class="content">content</div>
                        <slot name="footer"></slot>   <!--  有名插槽 -->
                        <slot>如果没有hello就显示slot的内容</slot>  <!--  匿名插槽   slot中可以设置默认内容,如果传递了内容则替换掉 -->
                   </div>`
    })
    var vm = new Vue({
        el: '#root'
    })
</script>
</body>

 3. 作用域插槽

固定写法:父组件中<template slot-scope="props"></template>      //props可以自定义用来接收子组件的数据

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

 

posted @ 2018-08-12 21:13  桑甚姑娘  阅读(190)  评论(0编辑  收藏  举报