当子组件需要向父组件传递数据时,就要用到自定义事件
子组件用 $emit()来触发事件,父组件用$on()来监昕子组件的事件
父组件也可以直接在子组件的自定义标签上使用 v-on 来监昕子组件触发的自定义事件,示例
代码如下:
父组件:
<template> <div class="hello"> {{totle}} <br> <HellowworldComponent msgparent="来自helloworld的信息" @increase='handleGetTot' @reduce='handleGetTot' /> </div> </template> <script> import HellowworldComponent from './views/HellowworldComponent'; export default { props:['msgp'], name: 'HelloWorld', data () { return { totle:0 } }, components:{ HellowworldComponent }, methods:{ handleGetTot:function(a){ this.totle = a; } } } </script> <style scoped> </style>
子组件:
HellowworldComponent
<template> <div> {{msgparent}} <br> <button class="btn btn-info" @click="reduce">-</button> 子组件显示数字:{{num}} <button class="btn btn-info" @click="increase">+</button> </div> </template> <script> export default { props:{ msgparent:String }, name: 'HellowworldComponent', data () { return { num : 0 } }, methods : { reduce(){ this.num--; this.$emit('reduce',this.num); }, increase(){ this.num++; this.$emit('increase',this.num); } } } </script> <style scoped> </style>