官网的原文是这样的:
最初在 <slot> 标签中的任何内容都被视为备用内容。备用内容在子组件的作用域内编译,并且只有在宿主元素为空,且没有要插入的内容时才显示备用内容。
首先来看看我的代码结构:
模板:
<pre>
<div class="fathercomponent">
<h1>我是父组件的标题</h1>
<child-component>
<p>初始化内容1</p>
<p>初始化内容2</p>
</child-component>
</div>
</pre>
script部分:
<pre>
var child = {
template:'<div><h1>我是子组件的标题</h1><slot>只有没有初始化内容的时候我才会出现</slot></div>'
}
</pre>
<pre>
new Vue({
el:'.fathercomponent',
components:{
'child-component':child,
}
});
</pre>
运行效果如下:
![](https://img.haomeiwen.com/i4256553/4ebbc8f714b58371.png)
运行效果如预料中的一般。
于是我把p标签给注释掉:
![](https://img.haomeiwen.com/i4256553/a9615ca877bc12bc.png)
结果运行如下:
![](https://img.haomeiwen.com/i4256553/7616cb9fb7e59fe1.png)
slot里的内容并没有出现,p也没有消失
在这里我发现注释掉p是没有办法实现的,只有直接删除掉p才能使slot里的内容显示出来
![](https://img.haomeiwen.com/i4256553/d94a4d6563451f38.png)
再次运行效果如下:
![](https://img.haomeiwen.com/i4256553/97d7f51c6610aebd.png)
网友评论