Vue使用插槽slot、自定义事件内容分发

代码实现

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
</head>
<body>

<div id="app">
    <todo>
        <todo-title slot="todo-title" :title="title"></todo-title>
        <todo-items slot="todo-items" v-for="(item,index) in todoItems" :item="item" :index="index"
                    v-on:remove="removeItem(index)"></todo-items>
    </todo>
</div>


<script>

    Vue.component("todo", {
     
     
        template: '<div>\n' +
            '    <slot name="todo-title"></slot>\n' +
            '    <ul>\n' +
            '        <slot name="todo-items"></slot>\n' +
            '    </ul>\n' +
            '</div>'
    });

    Vue.component("todo-title", {
     
     
        props: ['title'],
        template: '<div>{
     
     {title}}</div>'
    });

    Vue.component("todo-items", {
     
     
        props: ['item', 'index'],
        template: '<li>{
     
     {item}}&nbsp;&nbsp;&nbsp;<button @click="remove">删除</button></li>',
        methods: {
     
     
            remove: function (index) {
     
     
                this.$emit('remove', index);
            }
        }
    });

    var vm = new Vue({
     
     
        el: '#app',
        data: {
     
     
            title: 'jyuxuan',
            todoItems: ['Java', 'JavaWeb', 'JavaEE']
        },
        methods: {
     
     
            removeItem(index) {
     
     
                this.todoItems.splice(index, 1);
            }
        }
    })

</script>


</body>
</html>

猜你喜欢

转载自blog.csdn.net/qq_43656233/article/details/107690077