vue插槽
什么是插槽,它是vue提出的一个概念,插槽用于决定将所携带的内容,插入到指定的某个位置,使得模块分块,具有模块化特质。
插槽就是Vue实现的一套内容分发的API,将<slot></slot>元素作为承载分发内容的出口。
1.默认插槽
正常来说我们在组件里编写东西,在组件内是不展示的


但是在组件内加上插槽:
<slot></slot>

我们在<Header></Header>内写的"插槽内容"起作用了!!!
没有插槽的情况下在组件标签内些一些内容是不起任何作用的;
当我在组件中声明了slot元素后,在组件元素内写的内容就会跑到它这里了!
2.具名插槽
具名插槽,就是给这个插槽起个名字
在组件中,我给插槽起个名字,一个名字叫"girl",一个名字叫"boy",还有一个不起名字。
然后再<Header></Header>内,slot属性对应的内容都会和组件中name一一对应。
而没有名字的,就是默认插槽!!



3.作用域插槽
作用域插槽--组件上的属性,可以在组件元素内使用(子组件数据给父组件用)
先看一个最简单的例子!!
<!-- MyComponent.vue --> # 子组件使用 <template> <div> <slot></slot> <!-- 默认插槽 --> <slot name="name"></slot> <slot name="footer" :info="footerInfo"></slot> <!-- 具名插槽,并传递数据 --> </div> </template> <script> export default { data() { return { footerInfo: '来自组件的 footer 信息' } } } </script> # 父组件使用 <template v-slot:footer="{info}"> <div>作用域插槽内容:{{ info }}</div> </template>

这个东西是不是似曾相识,你要是使用过element-ui的table的话.
slot的两种方式
<slot row="z" name="name"></slot>
<slot row="4*********" name="qq"></slot>
<template slot="name" slot-scope="{row}">{{row}}</template>
<template v-slot:qq="{row}">{{row}}</template>

插槽透传demo
1、父亲辈parent.vue
<Setting > <div>我是默认插槽的内容111</div> <template #name> <div>777</div> </template> <template v-slot:footer="{info}"> <div>作用域插槽内容:{{ info }}</div> </template> </Setting>
2、子辈child.vue
<topicSetting>
<template
v-for="(slotFn, name) in $scopedSlots"
v-slot:[name]="slotProps"
>
<slot :name="name" v-bind="slotProps"></slot>
</template>
</topicSetting>
3、孙辈grandson.vue
<!-- MyComponent.vue -->
<template>
<div>
<slot></slot> <!-- 默认插槽 -->
<slot name="name"></slot>
<slot name="footer" :info="footerInfo"></slot> <!-- 具名插槽,并传递数据 -->
</div>
</template>
<script>
export default {
data() {
return {
footerInfo: '来自组件的 footer 信息'
}
}
}
</script>
vue3的插槽透传就比较简单了
1.也是循环,不过循环的是$slots,跟上述循环一致
2.使用js
<template> <Comp> </Comp> </template> <script setup> import TopicSetting from './topicSetting' import { h, useAttrs, useSlots} from 'vue' const Comp = h(TopicSetting, useAttrs(), useSlots()) </script>
3.动态组件
<template> <compent :is="h(TopicSetting, $attrs, $slots)"> </compent > </template> <script setup> import TopicSetting from './topicSetting' import { h} from 'vue' </script>
浙公网安备 33010602011771号