获得$emit对应函数的返回值
- 大概的问题就是, 子组件
Avatar触发了父组件Info的回调, 希望拿到回调函数的返回值进而拿到父组件的某些信息, 比如-
下面是子组件
-
<template> <div style="background-color: skyblue;"> <div>我是Avatar-子组件</div> <button @click="getParentInfo">点我获取信息</button> </div> </template> <script> export default { data() { return { } }, methods: { getParentInfo() { const returnValue = this.$emit('getInfo'); console.log('返回值是', returnValue); } } } </script> -
下面是父组件
-
<template> <div style="background-color: pink; padding-bottom: 1rem;"> <div>我是Info-父组件</div> <Avatar @getInfo="getInfoCallback"></Avatar> </div> </template> <script> import Avatar from './Avatar.vue'; export default { components: { Avatar, }, data() { return { name: 'hello, world' } }, methods: { getInfoCallback() { return this.name; } } } </script> -

-
可以看到,
$emit返回的并不是父组件的name属性, 而是子组件实例
-
- 如果要解决这个问题, 我们可以将一个函数作为参数传进去, 比如
- 子组件
-
methods: { getParentInfo() { this.$emit('getInfo', (name) => { console.log('这次拿到了 ', name); }); } } - 父组件: 在接收参数的同时调用
-
methods: { getInfoCallback(callback) { callback(this.name); } } 
本文介绍了在Vue组件中,子组件通过$emit触发父组件回调函数时,如何正确处理并获取返回值的问题,包括使用参数传递和回调机制。
884

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



