为什么要有插槽?
- 父组件代码
<div class="hello">
父组件展示
<child>
<p>想在子组件上展示一点东西</p>
</child>
</div>
- 子组件代码
<template>
<div>
子组件展示
</div>
</template>
<script>
export default {
name: "child"
};
</script>
-
展示效果
- 未实现的效果
<p>想在子组件上展示一点东西</p>
这一行文字没有展示
上述例子中,组件标签内的任何内容是不起任何作用的;想要实现理想的效果,必须使用
插槽
。
插槽使用
- 父组件代码(没发生变化)
<div class="hello">
父组件展示
<child>
<p>想在子组件上展示一点东西</p>
</child>
</div>
- 子组件代码
<template>
<div>
子组件展示
<slot></slot>
</div>
</template>
<script>
export default {
name: "child"
};
</script>
-
展示效果
- 使用插槽的方式
在子组件里面使用<slot></slot>
,<slot>
元素是承载分发内容的出口。
例子详解
- 父组件在引用子组件
child
时,希望向child
传递模板内容<p>测试一下吧内容写在这里了能否显示</p>
; - 让父组件传过来的模板内容在所在的位置显示;
-
child
中的<slot>
就是一个槽,可以接收父组件传过来的模板内容,然后用模板内容替换<slot>
-
child
如果没有包含一个<slot>
元素,则该组件起始标签和结束标签之间的任何内容都会被抛弃。
网友评论