WARNING
May Cause:
<parent-component>
<child-component>
<grand-child-component />
$props
$props
$emit
$emit
</child-component>
</parent-component>
Pros:
Challenging when your app gets larger, and you need data in a deeply nested component.
Cons:
<fox-component />
<whale-component />
<unicorn-component />
Vuex $store
state
state
state
mutation
mutation
mutation
<walking-tree-component>
<raccoon-component>
<laser-pew-pew-component />
$root.bitOfData
</raccoon-component>
</walking-tree-component>
<walking-tree-component>
<raccoon-component>
<laser-pew-pew-component />
$root.bitOfData?
</raccoon-component>
</walking-tree-component>
<galaxy-guardians>
</galaxy-guardians>
<parent-component>
<child-component>
<grand-child-component />
$parent.knowledge
$parent.$parent.knowledge
(Has a bit of data called knowledge)
</child-component>
</parent-component>
<parent-component>
<grand-child-component />
$parent.$parent.knowledge?
</parent-component>
<parent-component>
<grand-child-component />
provide
inject
<child-component>
<grand-parent-component>
</child-component>
</parent-component>
</grand-parent-component>
<providing-component>
<injecting-component />
<child-component>
<child-component>
<root-component>
provides.bit_of_data
inject:['bit_of_data']
provides.bit_of_data
provides.bit_of_data
this.bit_of_data
</child-component>
</child-component>
</providing-component>
</root-component>
ReactiveProvide.vue
import {ref, provide} from 'vue';
export default {
setup(){
const text = ref('Hello World');
provide('text', text);
return {text}
},
}
Vue 2 + 3
Vue 3 Composition API
export default {
data() {
return {
text: "Hello World",
}
},
provide() {
return {
getText: ()=>this.text,
setText: v=>this.text=v,
}
},
}
ReactiveInject.vue
import {inject} from 'vue'
export default {
name:"reactive-inject",
setup(){
const text = inject('text');
return {text};
},
}
Vue 2 + 3
Vue 3 Composition API
export default {
name:"reactive-inject",
inject: [
"getText",
"setText",
],
computed: {
text: {
get() {
return this.getText()
},
set(d) {
this.setText(d)
},
}
},
}
Reactive Provide/Inject
A good example is compound components where the children components only function inside of their parent components.
Another good example is using it for a
Global or Local Store
Let's look at an example using an accordion and splitting it up into compound components.
The following example was blatantly stolen from
Cassidy Williams' React Hooks Workshop
Follow Cassidy, because she is awesome:
twitter: cassidoo
An Accordion
AccordionWrapper
AccordionSection
AccordionTitle
AccordionContent
Bring it Home - All Together
The Counter Component
Our "CounterProvide" Data Layer Component
Our "CounterDisplay" Component
Our "CounterButtons" Update Component
The Fully Realized Counter Component