Vue.js 自定义事件

2019-08-21  本文已影响0人  Rinaloving
自定义事件

当子组件需要向父组件传递数据时,就要用到自定义事件。指令 v-on 除了监听 DOM 事件外,还可以用于组件之间的自定义事件。
Vue 组件也有与之类似的一条模式,子组件用 emit() 来触发事件,父组件用 on()来监听子组件的事件。
父组件也可以直接在子组件的自定义标签上使用 v-on 来监听子组件触发的自定义事件,示例:


<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>自定义事件</title>
</head>
<body>

    <!--自动识别最新稳定版本的Vue.js-->
    <script src="https://unpkg.com/vue/dist/vue.min.js"></script>
    <div id="app">
        <p>总数:{{ total }}</p>
        <my-component
                @increase="handleGetTotal"
                @reduce="handleGetTotal"></my-component>
    </div>

    <script>
        Vue.component('my-component',{
            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>
    

</body>
</html>

自定义事件.png
上一篇 下一篇

猜你喜欢

热点阅读