希望这个示例对你有帮助
// app.ux (使用发布订阅模式)
/**
* 应用级别的配置,供所有页面公用
*/
import axios from 'axios'
const pubSub = {
subscribers: {
any: []
},
subscribe: function(fn, type) {
type = type || 'any';
if (typeof this.subscribers[type] === 'undefined') {
this.subscribers[type] = [];
}
this.subscribers[type].push(fn);
},
unsubscribe: function(fn, type) {
this.visitSubscribers('unsubscribe', fn, type);
},
publish: function(publication, type) {
this.visitSubscribers('publish', publication, type);
},
visitSubscribers: function(action, arg, type) {
const pubtype = type || 'any';
const subscribers = this.subscribers[pubtype];
for (let i = 0; i < subscribers.length; i++) {
if (action === 'publish') {
subscribers[i](arg);
} else {
if (subscribers[i] === arg) {
subscribers.splice(i, 1);
}
}
}
}
};
/* @desc: 注入方法至全局 global,以便页面调用 */
const hook2global = global.__proto__ || global
hook2global.$pubSub = pubSub
export default {
async onCreate() {
const data = await axios('https://webapi.sporttery.cn/gateway/lottery/getHistoryPageListV1.qry?gameNo=350133&provinceId=0&pageSize=30&isVerify=1&pageNo=1')
hook2global.$pubSub.publish(data)
}
}
// 其他页面使用app.ux里面的数据
export default {
onInit(){
$pubSub.subscribe(this.getData)
},
getData(data){
console.log(data)
}
} |