天天看點

【Vue2.0學習】—插槽(六十四)

【Vue2.0學習】—插槽(六十四)

  • 作用:讓父元件可以向子元件指定的位置插入html結構,也是一種元件間通信的方式,适用于 父元件=》子元件
  • 分類:預設插槽、具名插槽、作用域插槽

預設插槽

使用方式:

【Vue2.0學習】—插槽(六十四)

具名插槽

【Vue2.0學習】—插槽(六十四)

作用域插槽

了解:資料在元件的自身,但根據資料生成的結構需要元件的使用者來決定。(games資料在Category元件中,但使用資料所周遊出來的結構由APP元件決定)

【Vue2.0學習】—插槽(六十四)
【Vue2.0學習】—插槽(六十四)

App.vue

<template>
    <div class="app">


        <Category title="遊戲">
            <template scope="play">
                <ul>
                    <li v-for="(g,index) in play.games" :key="index">{{g}}</li>
                </ul>
            </template>
        </Category>

        <Category title="遊戲">
            <template scope="{games}">
                <ol>
                    <li style="color:red" v-for="(g,index) in games" :key="index">{{g}}</li>
                </ol>
            </template>
        </Category>

        <Category title="遊戲">
            <template slot-scope="{games}">
                <h4 v-for="(g,index) in games" :key="index">{{g}}</h4>

            </template>


        </Category>


    </div>

</template>

<script>
    import Category from './components/Category.vue'
    export default {
        name: 'App',
        components: {
            Category
        }


    }
</script>

<style>
    .app,
    .foot {
        display: flex;
        justify-content: space-around;

    }

    .app img {
        width: 200px;
        height: auto;
    }

    .fff a {
        margin-left: 30px;
    }

    .fff h4 {
        text-align: center;
    }
</style>      

Category.vue

<template>
    <div class="container">
        <h3>{{title}}分類</h3>
        <slot :games="games">我是預設類容</slot>
        <slot>

        </slot>

    </div>
</template>

<script>
    export default {
        name: 'Cateory',
        props: ['title'],
        data() {
            return {

                games: ['海綿寶寶', '寶寶巴士', '找你妹', 'LOL']

            }
        }


    }
</script>

<style>
    .container {
        background-color: skyblue;
        width: 200px;
        height: 300px;
    }

    h3 {
        text-align: center;
        background-color: orange;
    }
</style>