vue 返回時帶參數問題


百度了一些辦法,用$emit暫存,到返回后的頁面去接收,一直得不到數據。方法如下:

1. 聲明一個空的Vue模塊eventBus
import Vue from 'vue'
/** * 定義空的vue實例,作為 eventbus實現非父子組件之間的通信(vue2.x中去掉了broadcast) */ var eventBus = new Vue({}); export default eventBus;

2.通過eventBus.$emit傳參給上一個頁面

import eventBus from '../service/eventbus.js';
 
methods:{    //列表選中具體醫院的點擊事件
    goback(hospital){        //傳遞一個map,choiceHospital是key,hospital是value
        eventBus.$emit('target','2');        //調用router回退頁面
        this.$router.go(-1);
    }
}

3.頁面接收參數

import eventBus from '../eventbus.js';//每次激活時
created(){    //根據key名獲取傳遞回來的參數,data就是map
    eventBus.$on('target', function(data){        //賦值給首頁的附近醫院數據模型
        this.activeTab = data;
    }.bind(this));
},

 貌似需要使用keep-alive組件,由於一些限制,無法使用keep-alive。經過探索輸出,發現eventBus時間在created事件發生之前就已經被調用。解決方法如下:在后一個頁面created和mounted發生后前一個頁面銷毀之前發送數據

 beforeDestroy() {
       console.log('准備發送了!!!');
       eventBus.$emit('target', '2');
       eventBus.$off('target');
},

  參考文章:

Vue——eventBus使用,重復觸發

  https://blog.csdn.net/where_slr/article/details/101024169?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.channel_param&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.channel_param


免責聲明!

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



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