Is there a way to declare provision/injection in a Vue3 dynamic component outside of the host settings function?
P粉384366923
2023-08-30 09:41:50
<p>I'm creating a <code>Dynamic Component</code> in <code>Vue3</code>. I use <code>v-bind</code> to provide <code>props</code>. </p>
<pre class="lang-js prettyprint-override"><code><component :is='MyComponent' v-bind='myProps' />
</code></pre>
<p>I want to provide/inject</code> functionality using <code>. How can I put the properties I provide into the dynamic component. My dynamic component calls <code>inject</code> in the <code>setup</code> function and expects a </code> value for its child component <code>. </p>
<p>While this is not documented on Vue, I tried it without success: </p>
<pre class="brush:php;toolbar:false;"><component :is='MyComponent' v-bind='myProps' :provide='myProvidedProps'/></pre>
<p>Even tried putting the <code>provide</code> object into the <code>props</code> object. </p>
After browsing the Vue3 source code, there is no way to
provide
specifications directly in the template todynamic components
. It must be called in the settings function or options of the parent hosting the dynamic component, or in the settings or options of the dynamic component.The two options are:
provide
on the component that hosts the dynamic component.This doesn't work for me because my setter function is called before my dynamic component is activated; I also need the component type to be set along with the provided value.
My component
Now this has its problems, as each dynamic component now needs to be responsible for understanding and calling the incoming provider.
Solution 1
The solution to each component needing to know the value provided is to create an intermediate component that provides the value.
Available (intermediate components)
Use it like this:
Solution 2
A cleaner solution is to create a wrapper component, similar to how keep-alive works. The target component only needs to be put into the
default slot
.Provide.vue
and use it like this: