Loading

Vue笔记(五):自定义事件

 

时间:2022/01/15

 

首先给出示例代码,通过示例代码来说明为什么需要自定义事件:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>

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

    </div>
    
    <script src="https://cdn.bootcss.com/vue/2.5.16/vue.min.js"></script>

    <script>

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

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

        Vue.component("todo-list",{
            props: ["list"],
            template: '<li>{{list}}<button v-on:click="remove">删除</button></li>',
            methods: {
                remove: function(){
                    this.$emit("remove");
                }
            }
        });

        var vm = new Vue({
            el: "#app",
            data: {
                title: "图书列表",
                items: ["Java", "Python", "Linux"]
            },
            methods: {
                removeByIndex: function(index){
                    // 一次删除一个元素
                    this.items.splice(index, 1);
                }
            }
        });

    </script>


</body>
</html>

上面这段代码是在Vue笔记(四):插槽的基础上为每一个slot中的button按钮添加一个点击删除的函数。但是问题在于由于vm对象中的方法只能与前端进行交互,而相同的,组件component中的代码也只能与前端的代码进行交互,这就导致component中的代码无法直接调用vm对象中的删除函数,所以需要通过前端来实现一个中转,而自定义事件就能起到这样一个中转的作用。具体需要看<todo-list>标签中的代码,可以看到通过v-on将自定义的事件remove与vm对象中的removeByIndex方法绑定在了一起,这样在component的remove方法中就可以通过this.$emit获取到自定义的remove事件,也就可以通过这个事件调用到vm中的removeByIndex方法了。

 

posted @ 2022-01-15 15:17    阅读(44)  评论(0编辑  收藏  举报