美文网首页
Vue自定义事件

Vue自定义事件

作者: ChasenGao | 来源:发表于2018-05-04 20:25 被阅读15次

在学习vue的过程中,发现这章内容没有过多的介绍。
于是根据理解写了一个例子:

    <div id="app">
        <compo v-on:myevent="total"></compo>
        <compo v-on:myevent="total"></compo>
        <p>你一共点了{{totalcount}}次</p>
    </div>
    <script type="text/javascript">
        var vm = new Vue({
            el:'#app',
            data:{
                totalcount:0    
            },
            components:{
                'compo':{
                    template:'<p v-on:click="counter">你点了我{{count}}次</p>',
                    props:{
                        count:{
                            type:Number,
                            default:0
                        }
                    },
                    methods:{
                        counter(){
                            this.count+=1;
                            this.$emit('myevent')
//                          自定义事件名称为myevent
                        }
                    }
                }
            },
            methods:{
                total(){
                    this.totalcount++;
                }
            }
            })
    </script>

在组件compo的methods中,定义了一个方法counter,每一次点击compo, count的值+1,因为在props中规定了count的属性为number类型,所以不会出现字符串拼接效果。
添加自定义事件myevent,在vue实例的methods中,定义方法total,并在compo的点击事件中调用。

相关文章

网友评论

      本文标题:Vue自定义事件

      本文链接:https://www.haomeiwen.com/subject/jodjrftx.html