javascript - Vue 从子组件向父组件暴露一个方法

标签 javascript vue.js vue-component

在以下方法中,您认为哪种方法更好??

[ 1 ] 使用$emit 将方法从子组件暴露给父组件

$emit('updateAPI',  exposeAPI({ childMethod: this.childMethod }))

[ 2 ] 使用父组件的$refs访问子组件方法

this.$refs.childComponent.childMethod() 

最佳答案

关于$refs,根据docs :

"$refs are only populated after the component has been rendered, and they are not reactive. It is only meant as an escape hatch for direct child manipulation - you should avoid accessing $refs from within templates or computed properties."

关于回调,我没有关于cons的信息,在this component的脚本部分有一个很好的例子。 Quasar Framework 的父组件通过发出一个名为 reset 的函数接收并可以分派(dispatch)此子函数。这就是为什么我认为这种方式更可取。

关于javascript - Vue 从子组件向父组件暴露一个方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55647325/

相关文章:

javascript - 在删除数组项之前添加 css 动画

javascript - Extjs 4.02 - 需要自定义组件

javascript - 如何识别arraybuffer是字符串还是图像?

javascript - 如何删除地址栏中的弹出窗口阻止程序

javascript - 变量名末尾有一个变量

vue.js - Vuetify v-data-table,如何在 HTML 中呈现标题文本?

vue.js - Vue 计算 setter 不适用于复选框?

javascript - 更新组件

laravel - 如何在VueJs中访问axios中的 `PromiseValue` `response`

vue.js - 存储有数据时如何调用函数