iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 18
4
Modern Web

用範例理解 Vue.js系列 第 18

用範例理解 Vue.js #18:Slot

Imgur

在 Vue 的 Component 中還有個好用的東西叫做 slot,當開發複雜或巢狀的 component 時,slot 不僅好用更增加了使用上的彈性。

基本上分為三種 slot

  • Single Slot
  • Named Slot
  • Scoped Slot

Single Slot

<h1>I'm the parent title</h1>
<my-component>
  <p>This is some original content</p>
  <p>This is some more original content</p>
</my-component>
Vue.component('my-component', {
  template:`
    <div class="child">
      <slot text="hello from child"></slot>
    </div>`
})

const vm = new Vue({
  el: '#app'
})

附上 fiddle (https://jsfiddle.net/hunterliu/08e5ssrk/)

Named Slot

<my-component>
  <h1 slot="header">Here might be a page title</h1>

  <p>A paragraph for the main content.</p>
  <p>And another one.</p>

  <p slot="footer">Here's some contact info</p>
</my-component>
Vue.component('my-component', {
  template:`
    <div class="container">
      <header>
        <slot name="header"></slot>
      </header>
      <main>
        <slot></slot>
      </main>
      <footer>
        <slot name="footer"></slot>
      </footer>
    </div>`
})

const vm = new Vue({
  el: '#app'
})

附上 fiddle (https://jsfiddle.net/hunterliu/816eckq7/)

Scoped Slot

範例一:

<app-layout>
  <template scope="props">
    <span>{{ props.text }}</span>
  </template>
</app-layout>
Vue.component('app-layout', {
  template: `
    <div class="layout">
      <h1>我是標題</h1>
      <p>我是內容</p>
      <slot text="我是app-layout slot"></slot>
    </div>
  `
});

const vm = new Vue({
  el: '#app'
});

附上 codepen (https://codepen.io/hunterliu1003/pen/VypeWm)

範例二:

<list :items="items">
  <template slot="item" scope="props">
    <li>id: {{props.id}}, text: {{props.text}}</li>
  </template>
</list>
Vue.component('list', {
  props: ['items'],
  template: `
    <ul>
      <slot name="item" v-for="item in items" :text="item.text" :id="item.id"></slot>
    </ul>`
});

const vm = new Vue({
  el: '#app',
  data: {
    items: [
      { id: 1, text: '項目 1' },
      { id: 2, text: '項目 2' },
      { id: 3, text: '項目 3' }
    ]
  }
});

附上 codepen (https://codepen.io/hunterliu1003/pen/QapyqZ)

官方 Modal 範例

https://jsfiddle.net/yyx990803/mwLbw11k/?utm_source=website&utm_medium=embed&utm_campaign=mwLbw11k

參考資料


上一篇
用範例理解 Vue.js #17:Global API(extend, nextTick, directive)
下一篇
用範例理解 Vue.js #19:Vuetify
系列文
用範例理解 Vue.js30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 則留言

0
kkdayy_55330
iT邦新手 5 級 ‧ 2019-02-04 13:04:00

全都範例沒說明特性?

0
小不釘
iT邦新手 2 級 ‧ 2019-09-06 14:49:03

我一開始也想說怎麼不定義一下slot是啥,不過我發現點進去範例看一看之後就很清楚了~
多謝樓主的撰文~

HunterLiu iT邦新手 4 級 ‧ 2019-09-08 14:54:47 檢舉

謝謝~文筆不好請見諒,我會繼續加油

我要留言

立即登入留言