鍍金池/ 問答/HTML/ vue slot嵌套

vue slot嵌套

父組件中有兩個(gè)子組件:子組件1 嵌套 子組件2
且子組件1 和 子組件2 都有<slot>

結(jié)果:
1.子組件1 slot不寫name ,子組件2 slot寫 name="content",
內(nèi)容可以正常渲染。

2.子組件1 slot寫name="panel" ,子組件2 slot寫 name="content",
只能渲染子組件1的插槽內(nèi)容。

3.子組件1 和 子組件2 slot都不寫 name,
內(nèi)容可以正常渲染。

請(qǐng)問:為什么會(huì)出現(xiàn)這種結(jié)果。

//子組件1: panel.vue
<template>
<div>
  <slot name="panel"></slot>
</div>
</template>

//子組件2 : content.vue
<template>
<div>
  <slot name="content"></slot>
</div>
</template>

//父組件
<template>
<panel>
  <h1 slot="panel">我是panel</h1>
  <content>
    <p  slot="content">我是content</p>
  </content>
</panel>
</template>

<script>
import Panel from '@/common/panel'
import Content from '@/common/content'
</script>
回答
編輯回答
她愚我

你是組件里面嵌套組件 第一種情況 panel不是具名插槽 相當(dāng)于 把整個(gè)

<h1 slot="panel">我是panel</h1>
<content>
<p slot="content">我是content</p>
</content>

插到panel div里面 你說panel組件<slot name="panel"></slot> 不寫name
<slot></slot> 那應(yīng)該渲染不出來 我是panel 這個(gè)h1吧

2017年11月14日 10:32
編輯回答
莓森

覺得可能是你panel下嵌套content的問題,可能是panel下嵌套content但沒有在panel里給content一個(gè)slot,才造成這樣的問題。

  1. 子組件1 slot不寫name ,子組件2 slot寫 name="content",內(nèi)容可以正常渲染。
    原因: 子組件1不寫name,此時(shí)的slot插槽內(nèi)容為原來子組件1 slot內(nèi)容及子組件2內(nèi)容.(匿名插槽)

2.子組件1 slot寫name="panel" ,子組件2 slot寫 name="content",只能渲染子組件1的插槽內(nèi) 容。
原因:具名插槽,只會(huì)顯示對(duì)應(yīng)內(nèi)容。此時(shí)slot是幫 <h1 slot="panel">我是panel</h1>占位。
3.子組件1 和 子組件2 slot都不寫 name,只能渲染子組件1的插槽內(nèi)容。
這個(gè)正常情況是都顯示,panel中的slot和情況一一樣,content中的slot按道理也能顯示對(duì)應(yīng)插槽內(nèi)容。(想不通)

2018年9月23日 16:02