vue自定义事件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=<device-width>, initial-scale=1.0">
    <script crossorigin="anonymous" integrity="sha512-BKbSR+cfyxLdMAsE0naLReFSLg8/pjbgfxHh/k/kUC82Hy7r6HtR5hLhobaln2gcTvzkyyehrdREdjpsQwy2Jw==" src="https://lib.baomitu.com/vue/2.6.12/vue.min.js"></script>
    <title>Document</title>
</head>
<body>
    <!-- view -->
    <div id="app">
        <one>
            <two slot="first" :name="username"></two>
            <three slot="second" :age="a" 
                :index="index" v-for="(a,index) in allages" 
                v-on:removesingle="removeage(index)"></three>
        </one>
    </div>
   
    <!-- viewmodel -->
    <script>
        //one 组件
        Vue.component("one",{
            template: '<div>
                        <slot name="first"></slot>
                        <ul>
                            <slot name="second"></slot>
                        </ul>
                       </div>'
        });

        //two 组件
        Vue.component("two",{
            props: ['name'],
            template: '<div>{{name}}</div>'
        })
        //three 组件
        Vue.component("three",{
            props: ['age','index'],
            template: '<li>{{index}}-------{{age}} <button v-on:click="remove">删除</button></li>',
            methods: {
                remove:function(index){
                    this.$emit('removesingle',index);
                }
            }
        })

        var vm  = new Vue({
            el:"#app",
            data:{
               username: "zhangsan",
               allages: [18,19,20],
            },
            methods: {
                removeage:function(index){
                    this.allages.splice(index,1)
                }
            }
        });
    </script>
</body>
</html>

  效果图:

   解释下上面的代码吧:

    首先我们希望是点击删除按钮,对应的数据能够被删除掉。

    要知道的是,我们点击删除按钮触发的函数只能在组件的methods方法里的,而不能直接调Vue对象的methods方法,所以只能通过中间的组件元素来帮助过渡。

    vue的methods方法可以直接获取到data中的数据,对它进行删除操作,又由于双向绑定,view层 的数据也会发生变化,这个也是我们想要的效果;但问题就是我们如何通过点击组件的删除按钮触发remove函数,在remove函数中如何去调用vue实例的removeage函数呢?这个时候就要用到自定义事件了,首先我们使用v-on绑定一个自定义的事件,当触发该事件时我们就可以调用removeage函数了,那这个事件要怎么触发呢?我们只要在remove函数中加上this.$emit('removesingle',index),就代表触发了removesingle事件,第二个参数是传给removesingle事件对应触发的removeage函数的参数。

原文地址:https://www.cnblogs.com/ibcdwx/p/14124038.html