Vue2 框架整理:子组件向父组件传递数据,$emit() 或 v-on

这里写图片描述

当子组件向父组件传递数据的时候,需要的是自定义事件: $on & $emit

子组件用$emit()触发事件, 父组件用$on() 监听子组件的事件

或者父组件也可以直接在子组件的自定义标签上使用v-on来监听子组件触发的自定义事件:

$emit() 中第一个参数是方法的名称,后面都是根据需求设定要传递的数据

比如: (下面所有 v-on 简写为语法糖@)


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #v1{
            display: none;
            width:200px;
            margin: 100px;
            border: 2px solid #faf;
        }
    </style>
</head>
<body>

<div id="v1">

    <v-component @add="sum" @reduce="sum"></v-component>

    <p>计算结果:{{ total }}</p>

</div>


<script src="vue.min.js"></script>
<script>
    window.onload=function () {
        document.getElementById("v1").style.display="block";
    };

    Vue.component('v-component',{
        template:'<div>'+
                    '<button @click="comPlus">点我加一</button> '+
                    '<button @click="comMinus">点我减一</button>'+
                  '</div>',
        data:function () {
            return{
                num:0
            }
        },
        methods:{
            comPlus:function () {
                this.num++;
                this.$emit('add',this.num);
            },
            comMinus:function () {
                this.num--;
                this.$emit('reduce',this.num);
            }
        }
    });

    var app=new Vue({
        el:"#v1",
        data:{
            total:0
        },
        methods:{
            sum:function (total) {
                this.total=total;
            }
        }
    })
</script>

</body>
</html>

实现效果:
这里写图片描述


猜你喜欢

转载自blog.csdn.net/freedomVenly/article/details/80875669