Vue插槽的理解和使用 Vue插槽的理解和使用_bobozai86的博客-优快云博客_vue插槽的使用
对于插槽的概念和使用,这是vue的一个难点,这需要我们静下心来,慢慢研究。以下是我这两天通过官网和其他资料的学习和使用总结出来的笔记,如有错误或者有不同见解的,欢迎留言,一起学习。
什么是插槽
插槽就是子组件中的提供给父组件使用的一个占位符,用<slot></slot> 表示,父组件可以在这个占位符中填充任何模板代码,如 HTML、组件等,填充的内容会替换子组件的<slot></slot>标签。
代码如下:
1、在子组件中放一个占位符
-
<template> -
<div> -
<h1>今天天气状况:</h1> -
<slot></slot> -
</div> -
</template> -
<script> -
export default { -
name: 'child' -
} -
</script>
2、在父组件中给这个占位符填充内容
-
<template> -
<div> -
<div>使用slot分发内容</div> -
<div> -
<child> -
<div style="margin-top: 30px">多云,最高气温34度,最低气温28度,微风</div> -
</child> -
</div> -
</div> -
</template> -
<script> -
import child from "./child.vue"; -
export default { -
name: 'father', -
components:{ -
child -
} -
} -
</script>
3、展示效果:


现在来看看,如果插槽中没有放入插槽,同样的父组件中在子组件中填充内容,会是啥样的:
-
<template> -
<div> -
<h1>今天天气状况:</h1> -
<!-- <slot></slot>--> -
</div> -
</template> -
<script> -
export default { -
name: 'child' -
} -
</script>

总结:如果子组件没有使用插槽,父组件如果需要往子组件中填充模板或者html, 是没法做到的
插槽的使用
插槽的最最简单使用,上面已有例子,这里就不写了,接下来看看,插槽其他使用场景
插槽使用 - 具名插槽
描述:具名插槽其实就是给插槽取个名字。一个子组件可以放多个插槽,而且可以放在不同的地方,而父组件填充内容时,可以根据这个名字把内容填充到对应插槽中。代码如下:
1、子组件的代码,设置了两个插槽(header和footer):
-
<template> -
<div> -
<div class="header"> -
<h1>我是页头标题</h1> -
<div> -
<slot name="header"></slot> -
</div> -
</div> -
<div class="footer"> -
<h1>我是页尾标题</h1> -
<div> -
<slot name="footer"></slot> -
</div> -
</div> -
</div> -
</template> -
<script> -
export default { -
name: "child1" -
} -
</script> -
<style scoped> -
</style>
2、父组件填充内容, 父组件通过 v-slot:[name] 的方式指定到对应的插槽中
-
<template> -
<div> -
<div>slot内容分发</div> -
<child1> -
<template slot="header"> -
<p>我是页头的具体内容</p> -
</template> -
<template slot="footer"> -
<p>我是页尾的具体内容</p> -
</template> -
</child1> -
</div> -
</template> -
<script> -
import child1 from "./child1.vue"; -
export default { -
name: "father1", -
components: { -
child1 -
} -
} -
</script> -
<style scoped> -
</style>
展示效果


本文详细介绍了Vue中的插槽概念及其使用方法,包括默认插槽和具名插槽的实践案例。通过示例展示了如何在子组件中定义插槽,以及父组件如何填充内容到插槽中,实现内容的分发。总结了如果子组件未使用插槽,父组件将无法向其添加模板或HTML内容。
6418

被折叠的 条评论
为什么被折叠?



