小编给大家分享一下vue如何从组件外部调用方法,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!
从组件外部调用方法
你可以通过给它一个从组件外部调用方法ref:
<!-- Parent.vue -->
<template>
<ChildComponent ref="child" />
</template>
// Parent.vue 中的某个地方
this.$refs.child.method();
通常,我们使用道具和事件在组件之间进行通信。道具被发送到子组件,事件被发送回父组件。
<template>
<ChildComponent
:tell-me-what-to-do="someInstructions"
@something-happened="hereIWillHelpYouWithThat"
/>
</template>
但有时你可能会遇到需要父组件触发子组件中的方法的情况。这是只有向下传递道具不起作用的地方。
可以向下传递一个布尔值并让子组件监视它:
<!-- Parent.vue -->
<template>
<ChildComponent :trigger="shouldCallMethod" />
</template>
// Child.vue
export default {
props: ['trigger'],
watch: {
shouldCallMethod(newVal) {
if (newVal) {
// 当触发器设置为 `true` 时调用该方法
this.method();
}
}
}
}
这工作正常,但仅限于第一次调用。如果你需要多次触发此操作,则必须清理并重置状态。然后逻辑看起来像这样:
Parent
组件传递true
给triggerprop
Watch
被触发,Child
组件调用方法
Child
组件发出一个事件告诉 Parent
组件该方法已成功触发
Parent
组件重置trigger
回false
,因此我们可以再次执行此操作
相反,如果我们在子组件上设置ref ,我们可以直接调用该方法:
<!-- Parent.vue -->
<template>
<ChildComponent ref="child" />
</template>
// Parent.vue 中的某个地方
this.$refs.child.method();
我们打破了“props down, events up
”规则,打破了封装,但它更清晰、更容易理解值得这样做!
以上是“vue如何从组件外部调用方法”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注天达云行业资讯频道!