2019-01-31 vue組件基礎(chǔ)篇2

子組件 ═══>向父組件傳遞數(shù)據(jù)時(shí),就要用到自定義事件
v-on除了監(jiān)聽DOM事件外,還可以用于組件之間的自定義事件

子組件用$emit()來觸發(fā)事件,父組件用$on()來監(jiān)聽子組件的事件

<div id="app">
    <p>總數(shù):{{ total }}</p>
    <ceshi @increase="handleGetTotal" @reduce="handleGetTotal"></ceshi>
</div>

<script>
    import Vue from 'vue'
    Vue.component('ceshi', {
        template: ' \
        <div> \
            <button @click="handleIncrease">+1</button> \
            <button @click="handleReduce">-1</button> \
        </div>',
        data: function () {
            return {
                counter: 0
            }
        },
        methods: {
            handleIncrease: function () {
                this.counter++;
                this.$emit('increase', this.counter);
            },
            handleReduce: function () {
                this.counter--;
                this.$emit('reduce', this.counter);
            },
        }
    });
    var app = new Vue({
        el: '#app',
        data: {
            total: 0
        },
        methods: {
            handleGetTotal: function (total) {
                this.total = total;
            }
        }
    })
</script>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容