vue插槽

vue插槽:在引入的組件標籤中書寫的內容是不會顯示的,若是要顯示這部份內容,須要用到<slot></slot>vue

 

一、插槽的概念:ide

好比說在Father組件中引入了Child組件,url

Father:對象

<template>
  <div>
    <Child url="http://www.baidu.com">
      <p>百度</p>
    </Child>
  </div>
</template>

Child:ip

<template>
  <div>
    <a :href="url" target="_blank">
      <slot></slot>
    </a>
  </div>
</template>
<script>
  export default {
    props: ['url']
  }
</script>

若是不在Child中寫slot標籤,那麼在Father組件中 <p>百度</p> 就不會有顯示作用域

 

二、具名插槽和匿名插槽:get

Father:it

<template>
  <div>
    <Child>
      <div slot="header">
        <h1>標題</h1>
      </div>
      <div>
        <p>內容</p>
      </div>
      <div slot="footer">
        <p>底部</p>
      </div>
    </Child>
  </div>
</template>

Child:class

<template>
  <div>
    <header>
      <slot name="header"></slot>
    </header>
    <main>
      <slot></slot>
    </main>
    <footer>
      <slot name="footer"></slot>
    </footer>
  </div>
</template>

此時,在父組件中的具名插槽和匿名插槽會對應地顯示在子組件相應的位置,注意2.6.0+版本後,父組件中的寫法:百度

<template>
  <div>
    <Child>
      <template v-slot:header>
        <h1>標題</h1>
      </template>
      <template>
        <p>內容</p>
      </template>
      <template v-slot:footer>
        <p>底部</p>
      </template>
    </Child>
  </div>
</template>

 

三、插槽做用域

前面父傳子使用的是props,那麼子傳父怎麼辦呢?

①先在子組件中用v-bind綁定一個屬性值

<template>
  <div>
    <a :href="url" target="_blank">
      <slot :val='"我是要傳給父組件的值"'></slot>
    </a>
  </div>
</template>

②在父組件中經過 v-slot='slotProps' 獲取到屬性集合對象

<template>
  <div>
    <Child v-slot='slotProps'>
      <p>{{slotProps.val}}</p>
    </Child>
  </div>
</template>

也能夠經過解構賦值的方式直接獲取到當前屬性

<template>
  <div>
    <Child url='xxx' v-slot='{val}'>
      <p>{{val}}</p>
    </Child>
  </div>
</template>

四、具名插槽做用域

Child:

<template>
  <div>
    <header>
      <slot name="header" :val='111'></slot>
    </header>
    <main>
      <slot :val='100'></slot>
    </main>
    <footer>
      <slot name="footer"></slot>
    </footer>
  </div>
</template>

Father:

<template>
  <div>
    <Child>
      <template v-slot:header={val}>
        <h1>標題</h1>
        <p>{{val}}</p>
      </template>
      <template v-slot='{val}'>
        <p>內容</p>
        <p>{{val}}</p>
      </template>
      <template v-slot:footer>
        <p>底部</p>
      </template>
    </Child>
  </div>
</template>