Prospect Tips
When learning provide and inject, I found a problem that the value passed by the top-level component using work provides is not responsive after receiving using inject in the base-level component. As shown in the following code
//Top component code const count = ref(100); provide('count-key',count); const setCount = ()=>{ = 99; } <template> <div>{{count}}</div>//99 </template> //Bottom component const count = inject('count-key'); const setCount = inject('set-count); onMounted(()=>{ setCount(); }) /*The onMounted function of the parent component is completed after the execution of the onMounted of the child component is completed, so the 100 displayed in the child component, but the value of count has been modified when displayed in the parent component, so the 99 displayed in the parent component and 100 displayed in the child component*/ <template> <div>{{count}}</div>//100 </template>
Solution
//Top component code const count = ref(100); provide('count-key',count); const setCount = ()=>{ = 99; return { countNum: } } provide('set-count',setcount) <template> <div>{{count}}</div>//99 </template> //Bottom component const count = inject('count-key'); const setCount = inject('set-count'); const countNum = setCount().countNum <template> <div>{{count}}--{{countNum}}</div>//100--99 </template> Used in subcomponentscountThe value is the same as the explanation of the above code,But the parent component'scountand subcomponentscountNumThe values are repackaged before displaying, so they are responsively changed
Thank you here for your help in blogger Jyann's article. Post a link here. The content is more comprehensive. If you have any related questions, please check it out.https:///javascript/
The above is the detailed explanation of the values of vue3 provide and inject underlying components that are not responsive. For more information about vue3 provide inject component values, please pay attention to my other related articles!