1. 程式人生 > >vue slot

vue slot

bsp child put 謝謝 rom 怎麽辦 log highlight spa

一般我發現slot都是用在子組件 不知道對不對,不對的請留言指教 ,謝謝謝謝

使用slot場景一:

子組件Minput.vue

<input type=‘text‘/>

 父組件 Minput

<Minput>可以顯示嗎</Minput>

 這種情況下 Minput標簽內的文字是不會渲染出來的

如果現在想在裏面把文字渲染出來怎麽辦

好 用slot

子組件

<input type=‘text‘/>
<slot></slot>

 這樣的話,父組件的裏面的文字就可以渲染出來

場景二:具名插槽

子組件 he.vue

<header>
    <slot name=‘header‘></slot>
</header>

 父組件

<he>
    <h1 name=‘header‘>hello world</h1>
</he>

  渲染出來的結果就是

<header><h1>hello world</h1></header>

  

場景三

子組件 child

<div>
    <h1>這是h1</h1>
    <slot>這是分發內容,只有在沒有分發內容的情況下顯示</slot>
</div>

  

父組件

<child>
    <p>這是一段p</p>
    <p>兩段p</p>
</child>

  

渲染出來就是

<div><h1>這是h1</h1><p>這是一段p</p><p>兩段p</p></div>

 

如果父組件

<child></child>

 

那麽渲染出來的就是

<div><h1>這是h1</h1>這是分發內容,只有在沒有分發內容的情況下顯示</div>

  

場景四:作用域插槽

子組件

<div class="child">
  <slot text="hello from child"></slot>
</div>

  

父組件

<div class="parent">
  <child>
    <template slot-scope="props">
      <span>hello from parent</span>
      <span>{{ props.text }}</span>
    </template>
  </child>
</div>

  

x渲染的話就是

<div class="parent">
  <div class="child">
    <span>hello from parent</span>
    <span>hello from child</span>
  </div>
</div>

  

  

vue slot