干貨-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>   

 

注意事項:

  使用該鈎子的頁面,在頁面銷毀時,也需要把該鈎子銷毀掉,否則每次進來都會獲取,會產生重復數據

 

分享一刻:

  sjci

  斯坦福大學推出的 JavaScript 加密庫,只有 6KB,API 也很簡單,但可以提供最佳的安全性。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM