The Context API allows passing data across components by defining a provider component to provide the data and then using the inject() function to access it in descendant components. The specific steps include: defining the provider component using the provide() function in the provider component. Use the inject() function to inject values in components that need to access shared data. Access the injected value.
Use Context to pass values in Vue
Context is an API in the Vue.js ecosystem that allows Pass data across components in the component tree. It does this by defining a value in the provider component and then accessing that value through the inject API in descendant components.
How to pass values using Context
Creating a provider component
Use the provide() function to define a provider component. This component will provide the data that needs to be shared.
<code class="javascript">import { provide } from 'vue'; export default { setup() { provide('myValue', 'Hello World!'); } }</code>
Inject value
In components that need to access shared data, use the inject() function to inject values.
<code class="javascript">import { inject } from 'vue'; export default { setup() { const myValue = inject('myValue'); return { myValue }; } }</code>
Accessing injected values
Injected values can now be accessed in a component's template or script.
<code class="html"><template> <h1>{{ myValue }}</h1> </template></code>
Example
Consider a component tree with parent and child components. The parent component provides a value 'myValue' that the child component needs to access.
Parent component (Provider.vue)
<code class="javascript"><script> import { provide } from 'vue'; export default { setup() { provide('myValue', 'Hello World!'); } } </script></code>
Child component (Consumer.vue)
<code class="javascript"><script> import { inject } from 'vue'; export default { setup() { const myValue = inject('myValue'); return { myValue }; } </script></code>
Result
When Consumer.vue renders, it will access the 'myValue' value provided by the parent component and display it in the UI.
The above is the detailed content of How to pass value from context in vue. For more information, please follow other related articles on the PHP Chinese website!