当前位置:网站首页>非父子组件的通信
非父子组件的通信
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) //取消监听边栏推荐
- SolidWorks GB Library (steel profile library, including aluminum profile, aluminum tube and other structures) installation and use tutorial (generating aluminum profile as an example)
- LC 面试题 02.07. 链表相交 & LC142. 环形链表II
- 一文带你了解静态路由的特点、目的及配置基本功能示例
- Bus message bus
- Problems and precautions about using data pumps (expdp, impdp) to export and import large capacity tables in Oracle migration
- 服装门店如何盈利?
- ANR 原理及实践
- 企業如何進行數據治理?分享數據治理4個方面的經驗總結
- 从零到一,教你搭建「CLIP 以文搜图」搜索服务(二):5 分钟实现原型
- 工具类:对象转map 驼峰转下划线 下划线转驼峰
猜你喜欢

MYSQL----导入导出&视图&索引&执行计划

Installing redis and windows extension method under win system

2018 Jiangsu Vocational College skills competition vocational group "information security management and evaluation" competition assignment

How can brand e-commerce grow against the trend? See the future here!

多个kubernetes集群如何实现共享同一个存储

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

网络基础 —— 报头、封装和解包

How can clothing stores make profits?

如何给目标机器人建模并仿真【数学/控制意义】

Basic introduction of JWT
随机推荐
MySQL的主从复制原理
Linear algebra (1)
Unity3d learning notes
oracle如何备份索引
MATLAB小技巧(29)多项式拟合 plotfit
2022年全国所有A级景区数据(13604条)
华为机试题素数伴侣
Prime partner of Huawei machine test questions
ViewModelProvider.of 过时方法解决
Anr principle and Practice
Mysql---- import and export & View & Index & execution plan
LVS+Keepalived(DR模式)学习笔记
Networkx绘图和常用库函数坐标绘图
服装门店如何盈利?
How can flinksql calculate the difference between a field before and after update when docking with CDC?
2018年江苏省职业院校技能大赛高职组“信息安全管理与评估”赛项任务书
工具类:对象转map 驼峰转下划线 下划线转驼峰
Master-slave replication principle of MySQL
Problems and precautions about using data pumps (expdp, impdp) to export and import large capacity tables in Oracle migration
根据IP获取地市