1. 程式人生 > >vue $emit

vue $emit

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8" />
    <title>Document</title>
</head>
<body>
    <div id="counter-event-example">
    <p>{{ total }}</p>
    <button-counter @increment1="incrementTotal1"></button-counter>
    <button-counter @increment2="incrementTotal2"></button-counter>
</div>
</body>
</html>
<script type="text/javascript" src="js/vue.js"></script>
<script type="text/javascript">
        Vue.component('button-counter', {
        template: '<button @click="increment">{{ counter }}</button>',
        data: function () {
            return {
                counter: 0
            }
        },
        methods: {
            increment: function () {
                this.counter += 1;
                this.$emit('increment1',"這個位子是可以加引數的");//觸發自定義increment1的函式。此處的increment1函式就是 incrementTotal1函式。
                this.$emit('increment2');

            }
        }
    });
    new Vue({
        el: '#counter-event-example',
        data: {
            total: 0
        },
        methods: {
            incrementTotal1: function (e) {
                this.total += 1;
                console.log(e);
            },
            incrementTotal2: function () {
                this.total += 1;
            }
        }
    })
</script>