子组件向父组件中传递事件、数据

举一个计算器的小例子:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<!--父组件模板-->
<div id="app">
   <child-cpn @increment="changeTotal" @decrement="changeTotal"></child-cpn>
   <h2>点击次数:{{total}}</h2>
</div>
<template id="childCpn">
    <div>
        <button @click="increment">+1</button>
        <button @click="decrement">-1</button>
    </div>
</template>
<script src="../js/vue.js"></script>
<script>
    let app=new Vue({
        el:'#app',
        data:{
            total:0
        },
        methods:{
            changeTotal(counter){
                this.total=counter;
             }
        },
        components:{
            'child-cpn':{
            template:'#childCpn',
            data(){
                return {
                   counter:0
                }
            },
            methods:{
                increment(){
                    this.counter++;
                    this.$emit('increment',this.counter)
                },
                decrement(){
                    this.counter--;
                    this.$emit('decrement',this.counter)
                }
            }
        }
    }




    })




</script>






</body>
</html>

运行结果:

原文地址:https://www.cnblogs.com/dongyaotou/p/13149603.html