Vue.js Components Communication Patterns (without Vuex) — Part 6
Context API pattern
So far the patterns introduced in the previous series are about “passing data” between components in a multi-level hierarchy. Could a parent component directly “provide” data and any descendant component just “consume” it? React.js has the context API to achieve it, what about Vue.js? The answer is Vue.js has a set of similar APIs.
Context API pattern
We will start with the similar component hierarchy as before where there are four nested components:
Here is the initial state of the components:
App has a set of desserts data.
ChildA are not doing anything, and in
GrandchildA, it wants to get the desserts data from
App and render it, but at the moment it cannot.
The initial view looks like this:
Now in order for
App to provide the desserts data to any descendant, we can use the
provide option. The
provide option can provide a set of data, or even the current component itself. Here we will just provide the whole
In the object returned in
provide(), we name the key as
app, and the value is
this that is pointing to the current
App instance. It is elegant and super simple to use.
GrandchildA that wants to consume the data (the data is on the
App instance, when we can get the
App instance, we can access its
data option), we will use the
The value of the key
inject could be an array or an object. Now the
App instance can be directly accessed in
GrandchildA! Therefore, we can iterate
app.desserts and render it on the page:
Also, we print out the
We can clearly see the
App instance and everything on it are there.
The concept of “Provide / Inject” in state management libraries such as Vuex and Redux
As stated in Part 1 of this series:
“Vuex is great for sharing data between components, but when it comes to some scenarios such as building a UI library or a state management library, Vuex is not suitable anymore, and we need to utilize the build-in mechanism of Vue itself.”
State management libraries such as Redux and Vuex all implement the concept of “Provide / Inject”. The instance of
store is injected into each component in the hierarchy:
Here are all the articles in this series: