vue插槽介绍

66 阅读2分钟

Vue中插槽介绍(默认插槽, 具名插槽, 作用域插槽):

什么是插槽?

在 Vue 中,插槽(slot)是一种机制,允许你在父组件中将子组件的内容进行分发和组合。通过插槽,你可以在子组件中定义一些可变的内容,然后在父组件中使用这个子组件时,动态地将内容填充到子组件中的指定位置。

下面介绍三类插槽: 默认插槽, 具名插槽, 作用域插槽

默认插槽

使用场景: 父组件传入一段内容给子组件,插入位置可以由子组件中使用slot来进行占位

<!-- 子组件 -->
<template>
  <br>
    <slot>我是子组件自己的内容</slot>     
</template>

其中子组件slot标签内部可以有内容,但是如果父组件有内容插入到子组件,则显示父组件传入的内容。

① 父组件未传入内容

<!-- 父组件 -->
<template>
    <div class="testslot">
        <h1>父组件</h1>
        <child></child>
    </div>
</template>

父组件未传入内容,则页面显示子组件自己的内容

image.png

② 父组件传入内容, 子组件代码不变

<!-- 父组件 -->
<template>
    <div class="testslot">
        <h1>父组件</h1>
        <child>我是父组件传入的内容</child>
    </div>
</template>

父组件传入内容,则页面显示子组件父组件传入的内容

image.png

具名插槽

具名插槽就是给插槽起了一个名称,代码中在slot中用name来体现

<!-- 子组件 -->
<template>
    <slot name="header">我是子组件的header</slot>     
    <br>
    <slot name="footer">我是子组件的footer</slot>     
</template>

子组件中有两个slot

<!-- 父组件 -->
<template>
    <div class="testslot">
        <h1>父组件</h1>

        <child>
            <template v-slot:header></template>

            <template v-slot:footer>父组件为footer填充内容</template>
        </child>
    </div>
</template>

父组件通过v-slot:name的值 来找子组件中对应的slot,并对其内容进行填充

页面效果

image.png

作用域插槽

作用域插槽就是给插槽绑定数据,可以通过v-bind来实现

<!-- 子组件 -->
<template>
    <slot name="header">我是子组件的header</slot>     
    <br>
    <slot name="footer" v-bind:footer="heading">我是子组件的footer</slot>     
</template>

其中父组件来接收

<!-- 父组件 -->
<template>
    <div class="testslot">
        <h1>父组件</h1>

        <child>
            <template v-slot:header></template>

            <template v-slot:footer="footerValue">
                {{footerValue}}
            </template>
        </child>
    </div> 
</template>

页面显示

image.png

总结:作用域插槽的主要作用就是为了实现: 在父组件中实现访问子组件的数据