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
Vue常见面试题汇总(附答案解析)Vue常见面试题汇总(附答案解析)Apr 08, 2021 pm 07:54 PM

本篇文章给大家分享一些Vue面试题(附答案解析)。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。

5 款适合国内使用的 Vue 移动端 UI 组件库5 款适合国内使用的 Vue 移动端 UI 组件库May 05, 2022 pm 09:11 PM

本篇文章给大家分享5 款适合国内使用的 Vue 移动端 UI 组件库,希望对大家有所帮助!

vue中props可以传递函数吗vue中props可以传递函数吗Jun 16, 2022 am 10:39 AM

vue中props可以传递函数;vue中可以将字符串、数组、数字和对象作为props传递,props主要用于组件的传值,目的为了接收外面传过来的数据,语法为“export default {methods: {myFunction() {// ...}}};”。

手把手带你利用vue3.x绘制流程图手把手带你利用vue3.x绘制流程图Jun 08, 2022 am 11:57 AM

利用vue3.x怎么绘制流程图?下面本篇文章给大家分享基于 vue3.x 的流程图绘制方法,希望对大家有所帮助!

聊聊vue指令中的修饰符,常用事件修饰符总结聊聊vue指令中的修饰符,常用事件修饰符总结May 09, 2022 am 11:07 AM

本篇文章带大家聊聊vue指令中的修饰符,对比一下vue中的指令修饰符和dom事件中的event对象,介绍一下常用的事件修饰符,希望对大家有所帮助!

如何覆盖组件库样式?React和Vue项目的解决方法浅析如何覆盖组件库样式?React和Vue项目的解决方法浅析May 16, 2022 am 11:15 AM

如何覆盖组件库样式?下面本篇文章给大家介绍一下React和Vue项目中优雅地覆盖组件库样式的方法,希望对大家有所帮助!

通过9个Vue3 组件库,看看聊前端的流行趋势!通过9个Vue3 组件库,看看聊前端的流行趋势!May 07, 2022 am 11:31 AM

本篇文章给大家分享9个开源的 Vue3 组件库,通过它们聊聊发现的前端的流行趋势,希望对大家有所帮助!

react与vue的虚拟dom有什么区别react与vue的虚拟dom有什么区别Apr 22, 2022 am 11:11 AM

react与vue的虚拟dom没有区别;react和vue的虚拟dom都是用js对象来模拟真实DOM,用虚拟DOM的diff来最小化更新真实DOM,可以减小不必要的性能损耗,按颗粒度分为不同的类型比较同层级dom节点,进行增、删、移的操作。

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool