Vue 作用域插槽複用模板-封裝for迴圈

書院二層樓發表於2020-10-02
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <title>作用域插槽複用模板-封裝for迴圈</title>
</head>
<body>
    <div id="test">

    </div>

    <script>

        //作用域插槽
        Vue.component("ComList", {
            props:["list"],
            template:`
            <div>
                <!-- 封裝for模板-->
                <ul v-for="(item,index) in list">
                    <li :key="index">
                        <slot name="itFor" :it="item"></slot>  
                    </li>
                </ul>
                    
            </div>
            `,
            data() {
                return {
                }
            },
        })
        const app = new Vue({
            el:"#test",
            data:{
                list:[
                    {
                        name:"Tom",
                        age:18,
                    },
                    {
                        name:"Jimmy",
                        age:28,
                    },
                    {
                        name:"Lily",
                        age:20,
                    },
                ],
            },
            template:`
            <div>
                <ComList :list="list">
                    <!-- 呼叫for模板中的插槽-->
                    <template v-slot:itFor="{it}">
                        <span v-if="it.age===18">
                            *************
                        </span>
                        <span v-else>
                            {{it.name}}---- {{it.age}}
                        </span>
                    </template>
                </ComList>
            </div>
            `
        })
    </script>
    
</body>
</html>

效果截圖:

相關文章