Vue-作用域插槽-列表組件
阿新 • • 發佈:2018-02-25
模板 ems orm 如何 win template tex http 官網
Vue 官網介紹作用域插槽時,
在 2.5.0+,
slot-scope
能被用在任意元素或組件中而不再局限於<template>
。作用域插槽更典型的用例是在列表組件中,允許使用者自定義如何渲染列表的每一項:
例子:
<my-awesome-list :items="items"> <!-- 作用域插槽也可以是具名的 --> <li slot="item" slot-scope="props" class="my-fancy-item"> {{ props.text }} </li> </my-awesome-list>
列表組件的模板:
<ul> <slot name="item" v-for="item in items" :text="item.text"> <!-- 這裏寫入備用內容 --> </slot> </ul>
其實到這裏,我自己倒騰了下,一開始沒有弄出來,後來理了理思緒才弄出來,完整代碼是這樣:
<parent-component v-bind:items="items"></parent-component>
window.onload = function() { Vue.component(‘parent-component‘, { template: ` <my-awesome-list :items="items"> <!-- 作用域插槽也可以是具名的 --> <li slot="item" slot-scope="props" > {{ props.text }} </li> </my-awesome-list> `, props: [‘items‘] }); Vue.component(‘my-awesome-list‘, { template: ` <ul> <slot name="item" v-for="item in items" :text="item.text"> <!-- 這裏寫入備用內容 --> </slot> </ul> `, props: [‘items‘] }); new Vue({ el: ‘#app‘, data: { items: [ { text: ‘111‘ }, { text: ‘222‘ }, { text: ‘333‘ } ] } }); };
當然,也可以這樣:
<my-awesome-list :items="items"> <!-- 作用域插槽也可以是具名的 --> <li slot="item" slot-scope="props"> {{ props.text }} </li> </my-awesome-list>
window.onload = function() { Vue.component(‘my-awesome-list‘, { template: ` <ul> <slot name="item" v-for="item in items" :text="item.text"> <!-- 這裏寫入備用內容 --> </slot> </ul> `, props:[‘items‘] }); new Vue({ el: ‘#app‘, data: { items: [ { text: ‘111‘ }, { text: ‘222‘ }, { text: ‘333‘ } ] } }); };
參考文檔:
https://cn.vuejs.org/v2/guide/components.html#作用域插槽
Vue-作用域插槽-列表組件