Vue 作用域插槽

时间:2022-01-26 06:11:18

使用场景:复用子组件的slot,又可以使slot的内容不一样。

<!DOCTYPE html>
<html lang="zh">

    <head>
        <meta charset="UTF-8" />
        <title>Vue</title>
    </head>

    <body>
        <div id="app">
            <my-component :books="books">
                <template slot="book" slot-scope="props">
                    <li>{{props.bookName}}</li>
                </template>
            </my-component>
        </div>
        <script src="https://cdn.bootcss.com/vue/2.5.9/vue.min.js"></script>
        <script type="text/javascript"> Vue.component('my-component', { template: ` <ul> <slot name="book" v-for="book in books" :book-name="book.name"><slot> </ul> `,
 props: { books: { type: Array, default: function() { return []; } } } }); new Vue({ el: "#app", data: { books: [{ name: 'css' }, { name: 'js' }, { name: 'html' }, ] } }) </script>
    </body>

</html>