揭示Vue内部组件API的三种方法
We’ve all been there, you got a component with an internal API (function or state) that you want to expose to the parent component, but with a lot of options to do so, which one is the best?
我们都遇到过这种情况,你有一个带有内部API(函数或状态)的组件,你想将其暴露给父组件,但有很多选项可以实现,哪个是最好的呢?
I recently answered a question on Twitter about this, and I thought it would be a good idea to write an article about it. Especially since we have more options in Vue 3 than we had in Vue 2 to tackle this problem.
最近我在Twitter上回答了一个关于这个问题的问题,我觉得写一篇文章是个好主意。特别是因为在Vue 3中,我们有比Vue 2更多的选项来解决这个问题。
Component API
组件 API
First, let’s define what a “component internal API” is. A component API usually consists of:
首先,让我们定义一下“组件内部API”是什么。组件API通常包括:
- State (props/data)
- 状态(props/data)
- Functions or methods
- 函数或方法
You are familiar with passing props to components to share state from parent to child, but what about the other way around? How can the child component pass back the state to the parent component?
你熟悉将props传递给组件以在父组件和子组件之间共享状态,但是反过来呢?子组件如何将状态传递回父组件?
You are also familiar with emitting events from child components to the parent, but what if the parent wants the child to execute a function? How can the parent component call a function on the child component?
你也熟悉从子组件向父组件发出事件,但是如果父组件希望子组件执行一个函数怎么办?父组件如何调用子组件上的函数?
So what we are discussing is the reverse of the “props-down events-up” principle, we want somehow to pass the state upwards and sort of emit events downwards but not exactly like that.
因此,我们讨论的是“自上而下传递props,自下而上传递事件”的相反原则,我们希望以某种方式向上传递状态,并在某种程度上向下发出事件,但不完全是这样。
Different nails, different hammers
不同的钉子,不同的锤子
There are a few ways we can expose an internal API to the parent component in Vue. Each excels in some cases and falls short in others.
在Vue中,我们有几种方式可以将内部API暴露给父组件。每种方式在某些情况下都表现出色,但在其他情况下则不足。
This is just my opinion on the features/patterns I’m going to discuss, you might have a different opinion and that’s fine. I’m just sharing my experience with these patterns and when I think they are best used.
这只是我对我将要讨论的特性/模式的观点,你可能有不同的观点,这是可以的。我只是分享我对这些模式的经验,以及我认为它们最适合使用的时机。