Vue中的插槽slot

218 阅读1分钟

一 场景

有三个vue组件且他们布局相同,布局如下图所示,底部均是导航栏,而上面的内容因为组件的不同而不同。 由于这三个组件的布局相同。因此为了避免重复将这三个组件的布局样式封装成Layout.vue组件。

二 代码

//Layout.vue
<template>
    <div class="nav-wrapper">
        <div class="content">
            <slot/>
            //这里用到了slot
        </div>
        <Nav/>
    </div>
</template>

<script lang="ts">
    export default {
        name: 'Layout'
    };
</script>

<style lang="scss" scoped>
    .nav-wrapper{
        border: 1px solid red;
        display:flex;
        flex-direction: column;
        height: 100vh;
        > .content{
            flex-grow: 1;
            overflow: auto;
        }
    }
</style>

三个组件中分别引用Layout组件,其中一个组件的代码如下所示。

//Money.vue
<template>
<Layout>
    money
    //Money组件自己的内容
</Layout>
</template>

<script lang="ts">
    export default {
        name: "Money",
    };
</script>

<style lang="scss" scoped>

</style>

三 用法总结

  1. Layout组件不知道谁会引用他,也不知道会在它的类为content的div中放什么内容,因此Layout组件中的slot是为了接收将来要放在这个位置的内容的。
  2. 当渲染到Money组件时,发现它使用了Layout标签,就会去渲染Layout组件,当运行到Layout组件中的slot标签时,又会去Money组件中找到Layout标签中的内容,用来替换slot。