Home > Web Front-end > Vue.js > Usage of provide and inject in vue

Usage of provide and inject in vue

下次还敢
Release: 2024-05-02 22:27:47
Original
1112 people have browsed it

provide and inject are methods for sharing data in Vue.js: provide() provides data in the parent component. inject() gets the data provided by the parent component in the child component. Features: Data is responsive and flows to the required location on demand without explicitly passing props.

Usage of provide and inject in vue

provide and inject in Vue.js

Question: What is Vue. provide and inject in js?

Answer: provide and inject are two global methods in Vue.js, used to share data between different components.

Detailed description:

provide

    ## is used in the parent component to provide data to its child components.
  • Use the provide() method in the parent component's setup() or created() method to provide data.
  • Syntax used:
  • provide('propertyName', value)

inject

    Use Get data from parent component in child component.
  • Use the inject() method in the setup() method of the subcomponent to obtain data.
  • Syntax used:
  • const propertyName = inject('propertyName')

Usage:

    In the parent component, use the provide() method to provide data:
  1. <code class="javascript">// 父组件
    export default {
      setup() {
        provide('sharedData', {
          message: 'Hello, world!'
        })
      }
    }</code>
    Copy after login
    In the child component, use the inject() method to obtain data:
  1. <code class="javascript">// 子组件
    export default {
      setup() {
        const sharedData = inject('sharedData')
        console.log(sharedData.message) // 输出: "Hello, world!"
      }
    }</code>
    Copy after login

Features:

    provide and inject allow data to flow on demand to the desired location in the component tree.
  • They can be used to share state, configuration items, or other data without explicitly passing props from component to component.
  • The shared data is responsive, when it changes in the parent component, the child component will automatically update.

The above is the detailed content of Usage of provide and inject in vue. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
vue
source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template