Vue之自定义事件详解,子组件与父组件之间的传值
最近学习vue看到自定义事件这里的时候卡住了,一开始理解不来,不知道父组件与子组件到底是什么,研究了一下,所以在这里分享我得出的结论,若有帮助就点个赞哈!
话不多说,直接上图:

以一个计数的实例跟大家讲解以下,大家留意一下我的代码注释:

<div id="app">
<div id="counter-event-example">
<p>{{ total }}</p>
//这里从vm中获得title1的值,在component实例中利用v-on:event-name绑定自定义的事件并触发函数incrementTotal且传入$emit()中携带的值
<button-counter v-bind:title='title1'v-on:increment="incrementTotal"></button-counter>
<button-counter v-on:increment="incrementTotal"></button-counter>
</div>
</div>
<script>
Vue.component('button-counter', {
//这里就在<template>中利用v-on:click触发函数incrementHandler间接触发函数中的$emit(),并向该函数传递了一个参数值
template: '<button v-on:click="incrementHandler">{{ counter }}</button>',
data: function () {
return {
counter: 0
}
},
methods: {
incrementHandler: function () {
this.counter += 1
//自定义$emit函数并传递counter属性的值
this.$emit('increment',this.counter)
}
},
})
new Vue({
el: '#counter-event-example',
data: {
data:'计数:',
total: 0
},
methods: {
//定义一个函数并定义一个参数接收$emit()传递过来的属性值
incrementTotal: function (c) {
this.total += 1
console.log(c)
}
}
})
</script>
本文深入解析Vue中自定义事件的使用,通过计数器实例详细阐述子组件如何通过$emit向父组件传递数据,以及父组件如何接收并处理这些数据。
1万+

被折叠的 条评论
为什么被折叠?



