子組件向父組件中傳遞事件、數據


舉一個計算器的小例子:

<!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>

運行結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM