其中eventName爲事件名,OBJECT爲觸發事件附加參數
示例代碼以下:微信
uni.$emit('update',{msg:'頁面更新'})
監聽全局自定義事件,事件由uni.$emit()觸發,回調函數會接收全部傳入的數。
eventName爲事件名,callback爲事件的回調函數。
示例代碼以下:函數
uni.$on('update',function(data){ console.log('監聽到事件來自 update ,攜帶參數 msg 爲:' + data.msg); })
實際開發中對於觸發頁面的動態更新將很是有效。
例如移動端項目經過本身編寫的組件替代tabbar進行tabar跳轉,恰逢這時某個頁面如微信支付成功,須要返回這個tabbar頁面,你會發現他不會像普通uni頁面(onshow生命週期)同樣會動態刷新,這就很影響用戶實際體驗。所以這個方法就頗有效,只須要在組件中寫入uni.$emit('update',{msg:'頁面更新'})而後在頁面使用uni.$on('update',function(data){ console.log('監聽到事件來自 update ,攜帶參數 msg 爲:' + data.msg); })接收,將函數寫入便可。實際應用例子以下:
組件中:微信支付
onShow() { switch (this.Tab){ case 'demo': uni.$emit('update',{msg:'頁面更新'}); break; } },
demo頁面中:this
created() { uni.$on('update', (res) => { this.list() console.log(res, '更新'); }) },
組件中觸發事件,demo頁面監聽事件,便可實現刷新!code