Home > Web Front-end > Vue.js > An article to talk about the use of provide and inject in Vue

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

青灯夜游
Release: 2023-04-10 18:52:13
forward
1344 people have browsed it

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);
Copy after login

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);
Copy after login

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

{{person.name}}---{{person.website}}
Copy after login

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

{{name}}--{{website}}
Copy after login
Copy after login

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

{{name}}--{{website}}
Copy after login
Copy after login

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)
Copy after login

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!

Related labels:
source:juejin.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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template