干货-vue 中使用 rxjs 进行非父子组件中传值
一.需求背景:
- 一般做 商城 项目都会有公共头部与底部组件,会抽出来在项目的最外层,而其他主体部分会在 <router-view class="main"></router-view> 中,
 - 有时主体部分与公共头部 或 底部会有数据交互,如商品分类列表的高亮,(点击主体部分,头部组件高亮),此时已不属于父子组件的数据传递,
 - 若将数据放到缓存中由于公共头部或底部一直都不会刷新,拿不到最新的数据,故不能实现,
 - 可以用vux,今天我们来学习用 rxjs 响应式编程库 来实现数据传输
 
二.先将rxjs封装成便于操作的类
- 安装依赖
 
npm install rxjs
- main.js中引入,并集成
 
import Vue from 'vue' import {subjectServer} from '@/utils/subject.server'; Vue.use(subjectServer);
- 在utils中创建 subject.server.js 封装类
 
import { Observable, BehaviorSubject } from 'rxjs';
class AjaxNoticeOneService {
  subject = new BehaviorSubject(0);
  pushParams(params) {
    this.subject.next(params);
  }
  clearParams() {
    this.subject.next(0);
  }
  getParams() {
    return this.subject.asObservable();
  }
}
export const subjectServer = {
    install(Vue, options) {
        Vue.prototype.$NotificationOneSub = new 
}
三.在需求页面使用
1.需求:
点击首页中的列表1的 更多, 跳转到详情页面,且header 上面的 列表1 高亮

 
2.分析页面

这个页面就是典型的 header + router-view 页面, router-view 中又包含 home + detail 页面
现在需要 home 与 header 之间传递数据
3.使用封装的方法
- 先在home中的点击事件中添加
 
this.$NotificationOneSub.pushParams({ key: "moduleActive",value: index})
- 再在 header 中接收这个方法
 
<script> import { filter } from "rxjs/operators"; export default { data(){ return { choosePage: -1, subscribeSub:null } }, mounted(){ this.subWatch() }, //销毁 destroyed() { if (this.subscribeSub != undefined) { this.subscribeSub.unsubscribe(); this.$NotificationOneSub.clearParams(); } }, methods: { //监听动态表单 接受从home 传来的数据(平行组件中使用甚佳) subWatch() { const self = this; //本地接收提交 this.subscribeSub = this.$NotificationOneSub .getParams() .pipe(filter(res => res !== 0)) .subscribe(item => { if (item.key === "moduleActive") { this.choosePage = item.value; // console.log(item.value); } }); }, } }; </script>
注意事项:
使用该钩子的页面,在页面销毁时,也需要把该钩子销毁掉,否则每次进来都会获取,会产生重复数据
分享一刻:
斯坦福大学推出的 JavaScript 加密库,只有 6KB,API 也很简单,但可以提供最佳的安全性。

                
            
        
浙公网安备 33010602011771号