子组件派发事件和值给父组件
2025/7/24原创小于 1 分钟约 248 字
1. 子组件派发事件和值给父组件
子组件通过$emit
派发事件和值给父组件(值可以有多个)
this.$emit('fnX', value)
父组件通过v-on
绑定子组件派发的事件,并触发一个新的事件,新的事件内可以接收传来的值
<ComponentName @fnX="fnY"></ComponentName>
methods: {
fnY(value) {
console.log(value)
}
}
1.1. 父子组件间传递数据 demo
<p class="codepen" data-height="400" data-theme-id="light" data-default-tab="js,result" data-user="xugaoyi" data-slug-hash="mdJVqgg" style="height: 400px; box-sizing: border-box; display: flex; align-items: center; justify-content: center; border: 2px solid; margin: 1em 0; padding: 1em;" data-pen-title="mdJVqgg">
<span>See the Pen <a href="https://codepen.io/xugaoyi/pen/mdJVqgg">
mdJVqgg</a> by xugaoyi (<a href="https://codepen.io/xugaoyi">@xugaoyi</a>)
on <a href="https://codepen.io">CodePen</a>.</span>
</p>
<script async src="https://static.codepen.io/assets/embed/ei.js"></script>