


How to use provide/inject in Vue to pass data across multiple layers of ancestors and descendants
Vue provides an efficient data transfer method - provide/inject, which can help us transfer data between ancestors and descendants across multiple layers, avoiding cumbersome props transfer. This article will introduce how to use provide/inject in Vue to achieve data transfer across multiple layers of ancestors and descendants.
1. Provide and inject
provide and inject are new APIs after Vue2.2.0 version, used to realize data transfer across multi-layer components. provide allows a component to inject a dependency into all its descendant components, and inject can receive this dependency and use it.
provide and inject are mainly used for high-order plug-in/component libraries, such as element-ui. In element-ui, its components all depend on a top-level component library. This component library needs to provide some public variables and methods to all sub-components. Provide and inject are used to transfer these data.
2. The use of provide and inject
Using provide in a component, we can provide an injection point for child components so that they can obtain the data provided by the parent component. For example:
// 父组件 export default { provide () { return { theme: this.theme } }, data () { return { theme: 'light' } } } // 子组件 export default { inject: ['theme'], mounted () { console.log(this.theme) // light } }
In the above example, the parent component uses provide to provide data and expose the data object to descendant components. The data here is a string type. The way to provide is to use the provide function. According to the official documentation of provide, the return value of this function is an object. The key in the object can be used when injecting descendants, and the value is the data to be injected, which can be a variable, function, etc.
Using inject in child components, we can receive data provided by parent components. For example:
export default { inject: ['theme'], mounted () { console.log(this.theme) // light } }
In the example, the child component receives data using the inject option in the component options. "inject: [key]" where key is the key of the data object to be exposed in the parent component. The key here is consistent with the one provided by the provide function. It is worth noting that by default, the dependency will be searched for in the parent. If you do not want to search in the parent, you need to set srcoll in the inject to false. Only data provided by the parent component can be injected by the child component.
3. Notes on provide and inject
- The data injected by provide can be used in descendant components, but not in its parent component.
In the mechanism of provide and inject, the data provided by provide can be injected into descendant components by inject. However, if inject is also used in the parent component to receive data, it will not take effect because inject will look for the provided data in the parent component by default, and Vue will not look in the parent component to be consistent with the descendant components. provide.
- Do not use arrow functions in provide to return data.
provide needs to return an object to provide data, so we often use arrow functions to return an object, for example:
export default { provide: () => ({ theme: 'light' }) }
However, in most cases we do not use arrows function to provide data, because arrow functions do not point to this. When using arrow functions in provide it does not get the correct context and it does not respond to data changes.
- It is not recommended to use names starting with the $ symbol in provide and inject.
Naming that starts with the $ symbol in provide and inject is a naming rule reserved by Vue, so we do not recommend using the $ symbol to start the provided data. Using names starting with the $ symbol in provide may cause some problems, while using names starting with the $ symbol in inject will be ignored.
4. Usage Scenarios
The main purpose of provide/inject is to build a component library across component levels. Specifically, multiple components share some of the same information or status, such as theme color, language, etc.
In the actual development process, a scenario can be easily imagined: in an App or a page, there may be many similar components. These components need to use the same state or method. We can use provide /inject to pass these shared information and status across levels, avoiding redundant code and duplication of work.
At the same time, we can also use mixins to avoid code duplication and code redundancy, making our code elegant, clean and easy to maintain.
5. Summary
Using provide/inject is an efficient data transfer method, which can help us realize data transfer across multiple layers of ancestors and descendants, and reduce the use of props. However, it should be noted that there are some precautions to follow when using provide/inject to avoid affecting the performance and correctness of the component. At the same time, actual application requires detailed analysis of scenarios and reasonable use of provide/inject, props, or vuex for data transfer.
The above is the detailed content of How to use provide/inject in Vue to pass data across multiple layers of ancestors and descendants. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

The watch option in Vue.js allows developers to listen for changes in specific data. When the data changes, watch triggers a callback function to perform update views or other tasks. Its configuration options include immediate, which specifies whether to execute a callback immediately, and deep, which specifies whether to recursively listen to changes to objects or arrays.

There are three ways to refer to JS files in Vue.js: directly specify the path using the <script> tag;; dynamic import using the mounted() lifecycle hook; and importing through the Vuex state management library.

Vue multi-page development is a way to build applications using the Vue.js framework, where the application is divided into separate pages: Code Maintenance: Splitting the application into multiple pages can make the code easier to manage and maintain. Modularity: Each page can be used as a separate module for easy reuse and replacement. Simple routing: Navigation between pages can be managed through simple routing configuration. SEO Optimization: Each page has its own URL, which helps SEO.

Vue.js has four methods to return to the previous page: $router.go(-1)$router.back() uses <router-link to="/" component window.history.back(), and the method selection depends on the scene.

You can query the Vue version by using Vue Devtools to view the Vue tab in the browser's console. Use npm to run the "npm list -g vue" command. Find the Vue item in the "dependencies" object of the package.json file. For Vue CLI projects, run the "vue --version" command. Check the version information in the <script> tag in the HTML file that refers to the Vue file.

Function interception in Vue is a technique used to limit the number of times a function is called within a specified time period and prevent performance problems. The implementation method is: import the lodash library: import { debounce } from 'lodash'; Use the debounce function to create an intercept function: const debouncedFunction = debounce(() => { / Logical / }, 500); Call the intercept function, and the control function is called at most once in 500 milliseconds.
