2-5 vue 自定义事件 event up

2017-09-05  本文已影响103人  codeTao

自定义事件 event up

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<div id="app">
    <p>{{ total }}</p>
    <button-counter v-on:clickcounter="clicktotal"></button-counter>
    <button-counter v-on:clickcounter="clicktotal"></button-counter>
</div>
<script src="js/vue.js"></script>
<script>
    // 1. 定义子组件
    Vue.component('button-counter', {
        template: '<button v-on:click="clickcounter">
                    {{ counter }}</button>',
        data: function () {
            return {
                counter: 0
            }
        },
        methods: {
            clickcounter: function () {
                this.counter += 1;
                // 触发事件
                this.$emit('clickcounter');
            }
        }
    })

    new Vue({
        el: '#app',
        data: {
            total: 0
        },
        methods: {
            clicktotal: function () {
                this.total += 1;
            }
        }
    })
</script>
</body>
</html>

运行结果:子组件已经和它外部完全解耦了。它所做的只是触发一个父组件关心的内部事件。

<strong>父组件模板的内容在父组件作用域内编译;子组件模板的内容在子组件作用域内编译</strong>

上一篇下一篇

猜你喜欢

热点阅读