slot-scope
一、基本資料傳遞
<html> <head> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> </head> <body> <div id="app"> <hello> <!-- 透過 <template> declare slot name 及要 use slot 的 data--> <template slot="say" scope="myscope"> <span>{{ myscope.mymes }}</span> </template> </hello> </div> <script> Vue.component('hello', { data: function () { return { message: 'Hello Bill' } }, template: ` <div> <!-- Slot 預設先 bind message --> <slot name="say" :mymes="message"></slot> </div> ` }); const vm = new Vue({ el: '#app', data: {} }); </script> </body> </html>
二、動態產生清單
<html> <head> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> </head> <body> <div id="app"> <!-- Pass Props 給 component --> <list :items="items"> <template slot="item" scope="props"> <li>@{{ props.text }}</li> </template> </list> </div> <script> Vue.component('list', { props: ['items'], template: ` <ul> <slot name="item" v-for="item in items" :text="item.text"></slot> </ul> ` }); const vm = new Vue({ el: '#app', data: { items: [ { id: 1, text: 'Hello' }, { id: 2, text: 'Hey' }, { id: 3, text: 'Haha' } ] } }); </script> </body> </html>
參考資料: