vue.js中$emit的理解

官网介绍比较简单

例子:$emit('increment1',[12,'kkk']),直接看是懵逼的有没有,可以先告诉你,就是触发自定义事件increment1(或者函数名吧),[]为参数

上案例

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <div id="counter-event-example">
            <p>{{ total }}</p>
            <button-counter v-on:increment1="incrementTotal"></button-counter>
            <button-counter v-on:increment2="incrementTotal"></button-counter>
        </div>
    </body>
    <script src="vue/vue.min.js"></script>
    <script>
        Vue.component('button-counter',{
            template:'<button v-on:click="increment">{{ counter }}</button>',
            data:function(){
                return {counter: 0}//组件数据就是这样的,函数式的,请注意
            },
            methods:{
                increment:function(){
                    this.counter += 1;
                    this.$emit('increment1',[12,'kkk']);//$emit
                }
            }
        });
        new Vue({
            el:'#counter-event-example',
            data:{
                total:0
            },
            methods:{
                incrementTotal:function(e){
                    this.total += 1;
                    console.log(e);
                }
            }
        });
    </script>
</html>

先看组件 button-counter

绑定了事件click————>increment

然后 this.counter += 1; this.$emit('increment1',[12,'kkk']);

这边就是触发事件 increment1,参考文献里面有点乱,这边是不是清晰多了

然后 <button-counter v-on:increment1="incrementTotal"></button-counter> 

v-on相当于监听吧,就触发 incrementTotal

输出// [12, "kkk"]

有没有很清晰,若有理解不对的地方,请指正






参考:http://arinu.me/?p=50

原文地址:https://www.cnblogs.com/hhweb/p/6678716.html