Vue关于插槽使用的一些总结

先看下官网的解释:Vue 实现了一套内容分发的 API,这套 API 的设计灵感源自 Web Components 规范草案,将 <slot> 元素作为承载分发内容的出口。
内容分发的概念: 将父组件的内容放到子组件指定的位置叫做内容分发

应用场景:

简而言之,插槽就是用来进行内容分发的。

image.png

具名插槽

例子:
// 父组件的内容
<template>
    <div class="home">
        <slotcenter>
            <template v-slot:header>
                <h1>this is header</h1>
            </template>
            <template v-slot:footer>
                <h1>this is footer</h1>
            </template>
            <template v-slot:default>
                <h1>default</h1>
            </template>
        </slotcenter>
    </div>
</template>

<script>
// @ is an alias to /src
import slotcenter from "@/components/slot.vue";

export default {
    name: "home",
    components: {
        slotcenter
    }
};
</script>
//子组件的内容
<template>
    <div>
        
        <slot name="footer">footer</slot>
        <slot name="header">header</slot>
        <slot>default</slot>
    </div>
</template>
<script>
export default {
    name: "slotcenter",
    components: {}
};
</script>
<style>
</style>

以上就是具名插槽的使用。

具名插槽和独占默认插槽的缩写语法

具名插槽缩写语法的例子
<template v-slot:footer>
       <h1>this is footer</h1>
</template>
//改成下面的形式
<template #footer>
     <h1>this is footer</h1>
</template>

独占默认插槽的缩写语法

在上述情况下,当被提供的内容只有默认插槽时,组件的标签才可以被当作插槽的模板来使用。这样我们就可以把 v-slot 直接用在组件上:

<current-user v-slot="slotProps">
  {{ slotProps.user.firstName }}
</current-user>
注意默认插槽的缩写语法不能和具名插槽混用,因为它会导致作用域不明确:
<!-- 无效,会导致警告 -->
<current-user v-slot="slotProps">
  {{ slotProps.user.firstName }}
  <template v-slot:other="otherSlotProps">
    slotProps is NOT available here
  </template>
</current-user>
只要出现多个插槽,请始终为所有的插槽使用完整的基于 <template> 的语法:
<current-user>
  <template v-slot:default="slotProps">
    {{ slotProps.user.firstName }}
  </template>

  <template v-slot:other="otherSlotProps">
    ...
  </template>
</current-user>

动态插槽名

<base-layout>
  <template v-slot:[dynamicSlotName]>
    ...
  </template>
</base-layout>

注意这里的dynamicSlotName不需要加引号

后备内容

就是默认值的意思,直接写在slot标签里即可

<slot name="slot1">默认值</slot>

作用域插槽

就是父组件能访问子组件数据的插槽。

相关概念

插槽prop: 绑定在 <slot> 元素上的特性.

例子
//子组件
<template>
    <div>       
        <slot name="footer" :age="age">footer</slot>
    </div>
</template>
<script>
export default {
    name: "slotcenter",
    data() {
        return {
            age: 12
        }
    }
};
</script>
<style>
</style>
//父组件
<template>
    <div class="home">
        <slotcenter>
            <template v-slot:footer="footprops">
                <h1>{{footprops.age}}</h1>
            </template>
        </slotcenter>
    </div>
</template>

<script>
// @ is an alias to /src
import slotcenter from "@/components/slot.vue";

export default {
    name: "home",
    data() {
        return {
        }
    },
    components: {
        slotcenter
   
    }
};
</script>

【完】

以上就是关于插槽的一些总结,如果不对或者需要补充地方欢迎留言~

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容