search
HomeWeb Front-endVue.jsAn article to talk about the use of provide and inject in Vue

How to use provide and inject in Vue? The following article will introduce to you how to use provide and inject in Vue. I hope it will be helpful to you!

An article to talk about the use of provide and inject in Vue

In vue2.0provide and inject are options (configuration)## The #API method is used in components to solve the problem of cross-component (grandparent and grandchild) communication.

is the communication between parent and child components. The parent component is listed through custom attributes. , and sub-components are received through

props. If you want to pass it layer by layer, this method will be more troublesome and inflexible

provide and inject are the solution: how to pass the data from the ancestor component to the grandchild component to realize the cross-level component transfer of data

In

vue3.0, the same provide and inject are provided, which are simpler and more convenient to use. From a purely conceptual perspective, they are relatively abstract and difficult to understand. [Related recommendations: vuejs video tutorial, web front-end development]

Still start from specific examples

provide() function

Definition: Provides a value that can be injected by descendant components

Implementation: The parent component has a provide, option to provide data, there is an inject option in the descendant component to start using the data passed by the parent component

provide (first parameter, second parameter) , receives two parameters, the first parameter is the key to be injected, it can be a string or a symbol, the second parameter is the value to be injected (Specific data to be passed to descendant components)

provide is the official componsition API provided by vue

Specific example The code is as follows

import {reactive,provide} from "vue";

let person = reactive({name: 'itclanCoder',website: 'https://coder.itclan.cn'});
provide('person',person);

It is enough to provide a value through the above

provide. Then how to pass this data to descendant components, then you need to use inject The

inject() function

Definition: Inject a value provided by an ancestor (parent) component or the entire application

Implementation: Receive the value passed by the parent (ancestor) component

inject(first parameter, second parameter (optional)): The first parameter is the injected key, which comes from the parent (ancestor) component. They both need to be consistent

Vue will traverse the parent component chain , determine the provided value by matching the key. If multiple components on the parent component chain provide the same key, then the closer one will overwrite the one provided by the component further on the chain. The value

If no value can be matched by

key, the inject() function will return undefined unless a default value# is provided. ##The second parameter is optional, that is, when no

key

is matched, the default value is used. It can also be a function to return some values ​​that are more complicated to create. If the default value itself is a function , then

false

must be passed in as the third parameter, indicating that this function is the default value, not a factory function and Similar to the

API

of registering life cycle hooks, inject() must be called synchronously in the setup() phase of the componentSpecific example code

import {inject,toRefs} from  "vue";

const person = inject('person');
// 若是使用解构,则会丢失响应式,修改数据时,页面不会更新,具体解决,可以引入toRef或toRefs函数
const {name,website} = toRefs(person);

The template in the grandchild component can be read, and the data passed from the parent component also supports responsiveness

{{person.name}}---{{person.website}}

If destructuring is used, variables can be used directly in the template

{{name}}--{{website}}

If destructuring is used, the variables can be used directly in the template

{{name}}--{{website}}

Note

If it is destructuring the variable and you want the data to be responsive, you need to use

toRef()

or toRefs()Convert data into responsivenessThe following is a complete example

import { inject } from 'vue'
import { fooSymbol } from './injectionSymbols'

// 注入值的默认方式
const foo = inject('foo') 

// 注入响应式的值
const count = inject('count')

// 通过 Symbol 类型的 key 注入
const foo2 = inject(fooSymbol)

// 注入一个值,若为空则使用提供的默认值
const bar = inject('foo', 'default value')

// 注入一个值,若为空则使用提供的工厂函数
const baz = inject('foo', () => new Map())

// 注入时为了表明提供的默认值是个函数,需要传入第三个参数
const fn = inject('function', () => {}, false)

Basically use the first method The most commonly used method of injecting default values ​​is to receive the passed value provided by the parent component

Summary

provide()

and inject() is relatively simple to use and is a way to solve cross-component communication. For components with deeper nesting levels, if the descendant component wants to use the data in the parent componentthen You can use this method to transfer data. This is still useful in some daily business development, and it is also a high-frequency interview question in interviews. How to solve cross-level components and non-parent-child component communication

(Learning video sharing:

vuejs introductory tutorial

, Basic programming video)

The above is the detailed content of An article to talk about the use of provide and inject in Vue. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
Netflix's Frontend: A Deep Dive into Its Technology StackNetflix's Frontend: A Deep Dive into Its Technology StackMay 08, 2025 am 12:11 AM

Netflix's front-end technology stack is mainly based on React and Redux. 1.React is used to build high-performance single-page applications, and improves code reusability and maintenance through component development. 2. Redux is used for state management to ensure that state changes are predictable and traceable. 3. The toolchain includes Webpack, Babel, Jest and Enzyme to ensure code quality and performance. 4. Performance optimization is achieved through code segmentation, lazy loading and server-side rendering to improve user experience.

Vue.js and the Frontend: Building Interactive User InterfacesVue.js and the Frontend: Building Interactive User InterfacesMay 06, 2025 am 12:02 AM

Vue.js is a progressive framework suitable for building highly interactive user interfaces. Its core functions include responsive systems, component development and routing management. 1) The responsive system realizes data monitoring through Object.defineProperty or Proxy, and automatically updates the interface. 2) Component development allows the interface to be split into reusable modules. 3) VueRouter supports single-page applications to improve user experience.

What are the disadvantages of VueJs?What are the disadvantages of VueJs?May 05, 2025 am 12:06 AM

The main disadvantages of Vue.js include: 1. The ecosystem is relatively new, and third-party libraries and tools are not as rich as other frameworks; 2. The learning curve becomes steep in complex functions; 3. Community support and resources are not as extensive as React and Angular; 4. Performance problems may be encountered in large applications; 5. Version upgrades and compatibility challenges are greater.

Netflix: Unveiling Its Frontend FrameworksNetflix: Unveiling Its Frontend FrameworksMay 04, 2025 am 12:16 AM

Netflix uses React as its front-end framework. 1.React's component development and virtual DOM mechanism improve performance and development efficiency. 2. Use Webpack and Babel to optimize code construction and deployment. 3. Use code segmentation, server-side rendering and caching strategies for performance optimization.

Frontend Development with Vue.js: Advantages and TechniquesFrontend Development with Vue.js: Advantages and TechniquesMay 03, 2025 am 12:02 AM

Reasons for Vue.js' popularity include simplicity and easy learning, flexibility and high performance. 1) Its progressive framework design is suitable for beginners to learn step by step. 2) Component-based development improves code maintainability and team collaboration efficiency. 3) Responsive systems and virtual DOM improve rendering performance.

Vue.js vs. React: Ease of Use and Learning CurveVue.js vs. React: Ease of Use and Learning CurveMay 02, 2025 am 12:13 AM

Vue.js is easier to use and has a smooth learning curve, which is suitable for beginners; React has a steeper learning curve, but has strong flexibility, which is suitable for experienced developers. 1.Vue.js is easy to get started with through simple data binding and progressive design. 2.React requires understanding of virtual DOM and JSX, but provides higher flexibility and performance advantages.

Vue.js vs. React: Which Framework is Right for You?Vue.js vs. React: Which Framework is Right for You?May 01, 2025 am 12:21 AM

Vue.js is suitable for fast development and small projects, while React is more suitable for large and complex projects. 1.Vue.js is simple and easy to learn, suitable for rapid development and small projects. 2.React is powerful and suitable for large and complex projects. 3. The progressive features of Vue.js are suitable for gradually introducing functions. 4. React's componentized and virtual DOM performs well when dealing with complex UI and data-intensive applications.

Vue.js vs. React: A Comparative Analysis of JavaScript FrameworksVue.js vs. React: A Comparative Analysis of JavaScript FrameworksApr 30, 2025 am 12:10 AM

Vue.js and React each have their own advantages and disadvantages. When choosing, you need to comprehensively consider team skills, project size and performance requirements. 1) Vue.js is suitable for fast development and small projects, with a low learning curve, but deep nested objects can cause performance problems. 2) React is suitable for large and complex applications, with a rich ecosystem, but frequent updates may lead to performance bottlenecks.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft