我理解 的vue2.6.0 的做用域插槽

寫這篇文章是由於本身在做用域插槽這裏用了較多時間,而後在論壇看的大可能是目前已廢棄的寫法。
本文的例子參考下面這篇文章的例子css

做用域插槽

<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Vue2.6.0做用域插槽</title>
        <script src="https://cdn.bootcss.com/vue/2.6.10/vue.common.dev.js"></script>
    </head>
    <body>
        <div id="app2">
            <!-- 組件使用者只需傳遞users數據便可 -->
            <my-stripe-list :items="users" odd-bgcolor="#D3DCE6" even-bgcolor="#E5E9F2">
                <!-- props對象接收來自子組件slot的myIndex對象,解構 -->
                <!-- 若是myIndex不加{},則能夠是任意值,例如js,則下邊[]內的myIndex都替換爲js.myIndex -->
                <template v-slot:leslie="{myIndex}">
                  
                   <span>{{users[myIndex].id}}</span>
                    <span>{{users[myIndex].name}}</span>
                    <span>{{users[myIndex].age}}</span>
                    <!-- 這裏能夠自定[編輯][刪除]按鈕的連接和樣式 -->
                    <a :href="'#edit/id/'+users[myIndex].id">編輯</a>
                    <a :href="'#del/id/'+users[myIndex].id">刪除</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="leslie" :myIndex="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>

子組件能夠不要名字:  <slot name="leslie" :myIndex="index"></slot>
對應的父組件的寫法爲:  <template v-slot="{myIndex}">
其實仔細一看,做用域插槽仍是比較簡單的,關鍵就是一句話: <template v-slot:leslie="{myIndex}">html

相關文章
相關標籤/搜索