当前位置:网站首页>Communication between non parent and child components

Communication between non parent and child components

2022-07-07 07:09:00 To be a woman of light

Here we mainly talk about two ways :

  • Provide/Inject
  • Mitt Global event bus ;

One 、Provide and Inject( Descendants )

Provide/Inject Used to share data between non parent and child components :

  • Such as the Some deeply nested components , The child component wants to get part of the content of the parent component ;
  • under these circumstances , If we still take props Gradually pass along the component chain , It's going to be a lot of trouble ;

In this case , We can use Provide and Inject:

  • No matter how deep the hierarchy is , The parent component can be used as the of all its child components Dependent provider ;
  • The parent component has one provide Options To provide data
  • The subcomponents are One inject Options To start using this data

Provide and Inject Use

  In real development provide The data in it is not written dead , From the server , At this time, if you want to get data The data in it ,vue It is suggested that it is best to proviede Write it as a function .

Process responsive data :

  Be careful : In the last case, our data is one-time , When our data changes ,Provide The data inside does not respond to changes ,(computed The arrow function is not bound this Of , That is to say, we now give length When you assign , Yes computed The return value of the function , because computed Inside this It's right data The value inside is dependent , Once the dependency changes ,computed The value of will be recalculated , There will be a new value , Will give you length Assign a new value .)

  Use :

Two 、 Global event bus mitt library

1. Install first  

npm install mitt -D

2. secondly , We can encapsulate a tool eventbus.js:

3. Use

Monitoring events : Monitor in the life cycle , Also get emitter object

  Mitt Event cancellation

// Cancel emitter All monitors in 
emitter.all.clear()
// Define a function 
function onFoo(){}
emitter.on('foo',onFoo) // monitor 
emitter.off('foo',onFoo) // Cancel monitoring 

原网站

版权声明
本文为[To be a woman of light]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207070312311768.html