Provide /inject and direct expose/import differences
Provide /inject tree structure, such as this example:
App.vue
<template>
<com-one-vue>
<com-two-vue></com-two-vue>
</com-one-vue>
<com-one-vue>
<com-three-vue></com-three-vue>
</com-one-vue>
</template>
<script setup>
import { provide, ref } from '@vue/runtime-core';
import comOneVue from './components/comOne.vue';
import comTwoVue from './components/comTwo.vue';
import comThreeVue from './components/comThree.vue';
</script>
Copy the code
comOne.vue
<template>
<slot></slot>
</template>
<script setup>
import { provide, ref } from "@vue/runtime-core";
provide('name',ref('one'))
</script>
Copy the code
comTwo.vue
<template> <div style="background:green;" > <p>comTwo</p> {{name}} </div> </template> <script setup> import { inject, ref } from "@vue/runtime-core"; const name = inject('name') </script>Copy the code
comThree.vue
<template> <div style="background:red;" > <p>comThree</p> {{name}} </div> </template> <script setup> import { inject } from "@vue/runtime-core"; const name = inject('name') name.value = 'one for three' </script>Copy the code
Then at this point:
We found that due to
The current structure is:
<com-one-vue>
<com-two-vue></com-two-vue>
</com-one-vue>
<com-one-vue>
<com-three-vue></com-three-vue>
</com-one-vue>
Copy the code
Two “component trees” are constructed so that data does not affect each other. The data in the comTwo is still coming from their own parents.
If we use export and inject at this time, it will obviously affect all the child components, even though their parent components are of the same class, but not the same.