插槽

插槽我对他的理解就是父组件的东西插到子组件的<slot></slot>里面,也不知道这样理解对不对,方便自己记忆

普通插槽


父组件如下:

<template>    <div class="father">        <h3>这里是父组件</h3>        <child>            <div>              <span>这是父组件插到子组件的slot标签</span>              <span>这是父组件插到子组件的slot标签</span>              <span>这是父组件插到子组件的slot标签</span>            </div>        </child>    </div></template><script>import child from './children'export default {    components: {        child    }}</script>

子组件如下:

<template>    <div>        <h3>这里是子组件,父组件的child将会插到slot标签里面</h3>        <slot></slot>    </div></template><script>export default {}</script>

显示效果如下:

具名插槽


父组件

<template>    <div class="father">        <h3>这里是父组件</h3>        <child>            <div>                <p>这不是具名插槽</p>                <p>这不是具名插槽</p>                <p>这不是具名插槽</p>            </div>            <div slot="havename">              <p>这是具名插槽</p>              <p>这是具名插槽</p>              <p>这是具名插槽</p>            </div>        </child>    </div></template><script>import child from './children'export default {    components: {        child    }}</script>

子组件

<template>    <div>        <h3>这里是子组件,父组件的child将会查到下面</h3>        <slot name="havename"></slot>        <slot></slot>    </div></template><script>export default {}</script>

效果如下:

作用域插槽


我对他的理解就是数据在子组件里面,父组件可以用

父组件

<template>    <div class="father">        <h3>这里是父组件</h3>        <child>            <div>                <p>这不是具名插槽</p>                <p>这不是具名插槽</p>                <p>这不是具名插槽</p>            </div>            <div slot="havename">              <p>这是具名插槽</p>              <p>这是具名插槽</p>              <p>这是具名插槽</p>            </div>            <template slot-scope="fromchildData">                <p v-for="(item,index) of fromchildData.data" :key="index">{{item}}</p>            </template>        </child>    </div></template><script>import child from './children'export default {    components: {        child    }}</script>

子组件

<template>    <div>        <h3>这里是子组件,父组件的child将会查到下面</h3>        <slot name="havename"></slot>        <slot></slot>        <slot :data="childData"></slot>    </div></template><script>export default {    data() {        return {            childData:[1,2,3,4,5]        }    },}</script>

效果如下: