本文介紹了如何理解Vue的作用域插槽的實(shí)現(xiàn)原理,分享給大家,也給自己留個(gè)筆記
舉個(gè)例子,比如我寫了一個(gè)可以實(shí)現(xiàn)條紋相間的列表組件,發(fā)布后,使用者可以自定義每一行的內(nèi)容或樣式(普通的slot就可以完成這個(gè)工作)。而作用域插槽的關(guān)鍵之處就在于,父組件能接收來自子組件的slot傳遞過來的參數(shù),具體看案例和注釋。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Vue作用域插槽</title> <script src="https://cdn.bootcss.com/vue/2.3.4/vue.js"></script> </head> <body> <div id="app2"> <my-stripe-list :items="users" odd-bgcolor="#D3DCE6" even-bgcolor="#E5E9F2"> <!-- props對(duì)象接收來自子組件slot的$index參數(shù) --> <template slot="cont" scope="props"> <span>{{users[props.$index].id}}</span> <span>{{users[props.$index].name}}</span> <span>{{users[props.$index].age}}</span> <!-- 這里可以自定[編輯][刪除]按鈕的鏈接和樣式 --> <a :href="'#edit/id/'+users[props.$index].id" rel="external nofollow" >編輯</a> <a :href="'#del/id/'+users[props.$index].id" rel="external nofollow" >刪除</a> </template> </my-stripe-list> </div> <script> Vue.component('my-stripe-list', { /*slot的$index可以傳遞到父組件中*/ template: ` <div> <div v-for="(item, index) in items" style="line-height:2.2;" :style="index % 2 === 0 ? 'background:'+oddBgcolor : 'background:'+evenBgcolor"> <slot name="cont" :$index="index"></slot> </div> </div> `, props: { items: Array, oddBgcolor: String, evenBgcolor: String } }); new Vue({ el: '#app2', data: { users: [ {id: 1, name: '張三', age: 20}, {id: 2, name: '李四', age: 22}, {id: 3, name: '王五', age: 27}, {id: 4, name: '張龍', age: 27}, {id: 5, name: '趙虎', age: 27} ] } }); </script> </body></html>效果如下:

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注