插槽,顾名思义留一个坑在组件中,然后动态的去填坑,例如:####

//Child.vue  子组件

<template>
    <div>
            <slot></slot>
    </div>
</template>
<script>
</script>
<style lang="">
    
</style>


//Parent.vue   引入子组件的文件

<template>
    <div>
            <my-child>
                    123
            </my-child>
    </div>
</template>
<script>
import Child from './Child'
export default {
   components: {myChild: Child}
}
</script>
<style lang="">
    
</style>

//这个时候,我们的页面就会显示123,在Child.vue中我们使用的slot就是坑位,在Parent.vue中,引用组件中传入的123就是填坑的内容,因为slot没有命名,这里称为不具名插槽

那么现在咱们来看看具名插槽的写法####

//Child.vue  子组件

<template>
    <div>
            <h1>--------------分割线--------------------</h1>
            <slot name="navBar"></slot>
            <h1>--------------分割线--------------------</h1>
            <slot name="endBar"></slot>
            <h1>--------------分割线--------------------</h1>
    </div>
</template>
<script>
</script>
<style lang="">
    
</style>

//Parent.vue   引入子组件的文件

<template>
    <div>
            <my-child>
                    <template slot="navBar">
                            234
                    </template>
                    <template slot="endBar">
                            345
                    </template>
            </my-child>
    </div>
</template>
<script>
import Child from './Child'
export default {
   components: {myChild: Child}
}
</script>
<style lang="">
    
</style>

//这个时候我们需要注意的是,在Child.vue中,用name来标识该插槽slot,而在使用中,我们用<template slot="表示名">来传入指定的插槽

还有一个插槽方式叫做作用域插槽####

//Child.vue  子组件

<template>
    <div>
             <!-- 这里的test作为键  ParentFromData 作为值返回给父组件 {test:  'Hello Vue!!!'}-->
            <slot :test="ParentFromData"></slot>
    </div>
</template>
<script>
export default {
    prop: ['ParentFromData']
}
</script>
<style lang="">
    
</style>


//Parent.vue   引入子组件的文件

<template >
    <div>
            <my-child :ParentFromData='data'>
                    <template slot-scope='ChildFromData'>
                          {{ChildFromData}}
                    </template>
            </my-child>
    </div>
</template>
<script>
import Child from './Child'
export default {
   data(){
        return{
            data: 'Hello Vue!!!'
        }
    }
   components: {myChild: Child}
}
</script>
<style lang="">
    
</style>

//此时的流程是,Parent.vue通过  prop 将 ParentFromData传递给Child.vue,而Child.vue拿到值以后将值赋值给test  形成键值对{test: 'Hello Vue!!!'} 返回给Parent.vue,从而页面显示的结果为{test: 'Hello Vue!!!'}
//我发现一个vue文件里面只能有一个作用域插槽
posted on 2018-12-15 18:58  佑之以航  阅读(468)  评论(0编辑  收藏  举报