当前位置:网站首页>非父子组件的通信
非父子组件的通信
2022-07-07 03:12:00 【要成为光的女人】
这里我们主要讲两种方式:
- Provide/Inject
- Mitt全局事件总线;
一、Provide和Inject(子孙级)
Provide/Inject 用于非父子组件之间共享数据:
- 比如有一些深度嵌套的组件,子组件想要获取父组件的部分内容;
- 在这种情况下,如果我们仍然将props沿着组件链逐渐传递下去,就会非常的麻烦;
对于这种情况下,我们可以使用Provide和Inject:
- 无论层级结构有多深,父组件都可以作为其所有子组件的依赖提供者;
- 父组件有一个provide 选项来提供数据
- 子组件有一个inject 选项来开始使用这些数据
Provide和Inject 的使用


在真实开发里面provide里面的数据不是写死的,可能来自于服务器,这时候要想拿到data里面的数据,vue建议最好将proviede写成一个函数。

处理响应式数据:
注意:上一案例中我们的数据一次性,当我们数据发生变化的时候,Provide里面的数据是无任何响应变化的,(computed箭头函数是不绑定this的,也就是说我们现在给length赋值的时候,是赋的computed函数的返回值,因为computed里面的this是对data里面的值是有依赖的,一旦依赖发生改变,computed的值就会重新计算,会有一个新的值,就会给length赋值新的值。)

使用:

二、全局事件总线mitt库
1.先安装
npm install mitt -D2.其次,我们可以封装一个工具eventbus.js:

3.使用

监听事件:在生命周期里监听,也是拿到emitter对象

Mitt事件取消
//取消emitter中所有的监听
emitter.all.clear()
//定义一个函数
function onFoo(){}
emitter.on('foo',onFoo) //监听
emitter.off('foo',onFoo) //取消监听边栏推荐
- Comment les entreprises gèrent - elles les données? Partager les leçons tirées des quatre aspects de la gouvernance des données
- Please tell me how to monitor multiple schemas and tables by listening to PgSQL
- LC 面试题 02.07. 链表相交 & LC142. 环形链表II
- Abnova循环肿瘤DNA丨全血分离,基因组DNA萃取分析
- 2018年江苏省职业院校技能大赛高职组“信息安全管理与评估”赛项任务书第一阶段答案
- Redhat5 installing vmware tools under virtual machine
- 剑指offer-高质量的代码
- 华为机试题素数伴侣
- Anr principle and Practice
- MySQL的主从复制原理
猜你喜欢

CompletableFuture使用详解

带你刷(牛客网)C语言百题(第一天)

基于JS的迷宫小游戏

Big coffee gathering | nextarch foundation cloud development meetup is coming

关于数据库数据转移的问题,求各位解答下

Linear algebra (1)

【NOI模拟赛】区域划分(结论,构造)

ESXI挂载移动(机械)硬盘详细教程

Jetpack compose is much more than a UI framework~

. Net 5 fluentftp connection FTP failure problem: this operation is only allowed using a successfully authenticated context
随机推荐
学术报告系列(六) - Autonomous Driving on the journey to full autonomy
After the promotion, sales volume and flow are both. Is it really easy to relax?
Sqlserver multithreaded query problem
linux系统rpm方式安装的mysql启动失败
Matlab tips (29) polynomial fitting plotfit
Please ask a question, flick Oracle CDC, read a table without update operation, and repeatedly read the full amount of data every ten seconds
Comment les entreprises gèrent - elles les données? Partager les leçons tirées des quatre aspects de la gouvernance des données
2022/07/04学习记录
How can brand e-commerce grow against the trend? See the future here!
impdp的transform参数的测试
Leetcode T1165: 日志分析
Basic introduction of JWT
libcurl返回curlcode说明
From zero to one, I will teach you to build the "clip search by text" search service (2): 5 minutes to realize the prototype
What books can greatly improve programming ideas and abilities?
一条慢SQL拖死整个系统
循环肿瘤细胞——Abnova 解决方案来啦
华为机试题素数伴侣
from . onnxruntime_ pybind11_ State Import * noqa ddddocr operation error
Initial experience of addresssanitizer Technology