Home >Web Front-end >Vue.js >How to pass value from context in vue

How to pass value from context in vue

下次还敢
下次还敢Original
2024-05-09 15:18:171276browse

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.

How to pass value from context in vue

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:How to write less in vueNext article:How to write less in vue