一.插槽是什么?
插槽就是子组件提供给父组件的占位符,用solt元素来表示
父组件可以在这个占位符里面填充给各种模板代码,那么这个填充的内容会替换到solt标签里
简而言之,就是子组件留了个坑,父组件可以使用指定的内容来填坑
二.插槽的类型:
1.匿名插槽
父组件:
<template>
//父组件
<div id="app">
<Comp>
<template >
<div>匿名插槽</div>
</template>
</Comp>
</div>
</template>
<script>
import Comp from './Comp.vue';
export default {
name: 'App',
components:{Comp}
}
</script>
<style>
</style>
<template>
<div>
<!-- 子组件 -->
<slot></slot><!-- 匿名插槽 -->
</div>
</template>
<script>
export default {
}
</script>
<style>
</style>
运行结果:
2.具名插槽
格式:v-slot:插槽名称 ,简写:#插槽名称
父组件:
<template>
<!-- 父组件 -->
<div id="app">
<Comp>
<template >
<div>匿名插槽</div>
</template>
<template #footer>
<div>footer的具名插槽</div>
</template>
<template #header>
<div>header的具名插槽</div>
</template>
</Comp>
</div>
</template>
<script>
import Comp from './Comp.vue';
export default {
name: 'App',
components:{Comp}
}
</script>
<style>
</style>
子组件:
<template>
<!-- 子组件 -->
<div>
<slot name="header"></slot><!-- 具名插槽 -->
<slot></slot><!-- 匿名插槽 -->
<slot name="footer"></slot> <!-- 具名插槽 -->
</div>
</template>
<script>
export default {
}
</script>
<style>
</style>
运行结果:
(不同的插槽来名称,排放的位置不一样)
3.作用域插槽:传递参数,父组件可以接收子组件传递的参数
格式:v-slot:插槽名称 = “props” 简写:#插槽名称 = “props”
父组件:
<template>
<!-- 父组件 -->
<div id="app">
<Comp>
<template >
<div>匿名插槽</div>
</template>
<template #footer>
<div>footer的具名插槽</div>
</template>
<template #header="props">
<div>作用域插槽</div>
<div>txt1:{{props.txt1}}</div>
<div>txt2:{{props.txt2}}</div>
</template>
</Comp>
</div>
</template>
<script>
import Comp from './Comp.vue';
export default {
name: 'App',
components:{Comp}
}
</script>
<style>
</style>
注:这个props相当于拿到了字段的那些属性值
子组件:
<template>
<!-- 子组件 -->
<div>
<!-- 子组件通过props传递txt1 -->
<slot name="header" :txt1="传递的参数1" :txt2="传递的参数2"></slot><!-- 作用域插槽 -->
<slot></slot><!-- 匿名插槽 -->
<slot name="footer"></slot> <!-- 具名插槽 -->
</div>
</template>
<script>
export default {
}
</script>
<style>
</style>
运行结果:
注意:
(1)v-slot是从2.6.0+开始使用的,在此版本之前用的是slot 和slot-scope
(2).vue3只能用v-slot
4.动态插槽名(就是将插槽名称变成一个变量)
格式:v-slot:[插槽名称变量] 简写:#[插槽名称变量]
父组件:
<template>
<!-- 父组件 -->
<div id="app">
<Comp>
<template >
<div>匿名插槽</div>
</template>
<template #[name]>
<div>footer的动态插槽名</div>
</template>
<template #header="props">
<div>作用域插槽</div>
<div>txt1:{{props.txt1}}</div>
<div>txt2:{{props.txt2}}</div>
</template>
</Comp>
</div>
</template>
<script>
import Comp from './Comp.vue';
export default {
name: 'App',
components:{Comp},
data(){
return{
name:'footer',
};
}
}
</script>
<style>
</style>
子组件:
<template>
<!-- 子组件 -->
<div>
<!-- 子组件通过props传递txt1 -->
<slot name="header" :txt1="传递的参数1" :txt2="传递的参数2"></slot><!-- 作用域插槽 -->
<slot></slot><!-- 匿名插槽 -->
<slot name="footer"></slot> <!-- 具名插槽 -->
</div>
</template>
<script>
export default {
}
</script>
<style>
</style>
运行结果: