Home > Article > Web Front-end > Learning about provide/inject in vue
This article shares with you the learning about provide/inject in vue, I hope it can help friends in need
I have been looking at the source code of element-ui recently. , I found such an attribute: inject. Then I checked the official website provider/inject
provider/inject: To put it simply, the variable is provided through provider in the parent component, and then injected through inject in the child component. variable.
It should be noted that no matter how deep the sub-component is, as long as inject is called, the data in the provider can be injected. Instead of being limited to getting data only from the prop attribute of the current parent component.
Let’s verify our conjecture:
first: define a parent component
<template> <p> <childOne></childOne> </p> </template> <script> import childOne from '../components/test/ChildOne' export default { name: "Parent", provide: { for: "demo" }, components:{ childOne } }
Here we are in the parent component Provide for this variable.
second defines a subcomponent
<template> <p> {{demo}} <childtwo></childtwo> </p> </template> <script> import childtwo from './ChildTwo' export default { name: "childOne", inject: ['for'], data() { return { demo: this.for } }, components: { childtwo } } </script>
third defines another subcomponent
<template> <p> {{demo}} </p> </template> <script> export default { name: "", inject: ['for'], data() { return { demo: this.for } } } </script>
In the two sub-components, we use jnject to inject the variable for provided by provide and provide it to the data attribute.
The official website here indicates that the example only works in Vue 2.2.1 or higher. Below this version, the injected value will be obtained after props and data are initialized.
Check the results after running
As can be seen from the above example, as long as it is called in the parent component, then in During the life cycle of this parent component, all child components can call inject to inject the value in the parent component.
Related recommendations:
vue 2 Using Bus.js to implement non-parent-child component communication
Chat example based on vue.js and webpack
Vue.js best practices (five tips to make you a Vue.js master)
The above is the detailed content of Learning about provide/inject in vue. For more information, please follow other related articles on the PHP Chinese website!