$emit
我们知道,父组件是使用 props 传递数据给子组件,但如果子组件要把数据传递回去,应该怎样做?那就是自定义事件!
使用 v-on 监听事件
使用 $emit 触发事件
$emit(事件名,传递的数据)
<div id="app"><p>{{todo}}</p><mycomponent @inset="adds"></mycomponent><mycomponent @inset="adds"></mycomponent>
</div>
<script>
var componentA = {data: function(){return{count: 0}},template: '<button @click="add" type="button">{{count}}</button>',methods: {add: function(){this.count++;// 触发自定义事件this.$emit('inset', this.count)}}
}
new Vue({el: '#app',data: {todo: 0},components: {// 引用组件'mycomponent': componentA},methods: {adds: function(num){this.todo++;console.log(num)}}
})
</script>