封装eventChannel 先 创建一个 eventChannel.js的文件
class Channel {
constructor(arg) {
type: 'Test'
}
// 接收值事件
eventOn(that, emitName, feedback) {
// #ifdef APP-NVUE
const eventChannel = that.$scope.eventChannel; // 兼容APP-NVUE
// #endif
// #ifndef APP-NVUE
const eventChannel = that.getOpenerEventChannel();
// #endif
let result = null;
eventChannel.on(emitName, res => {
// console.log(res);
result = res;
})
return feedback(result);
}
// 发送事件 不跳页面
eventEmit(that, emitName, data) {
// #ifdef APP-NVUE
const eventChannel = that.$scope.eventChannel; // 兼容APP-NVUE
// #endif
// #ifndef APP-NVUE
const eventChannel = that.getOpenerEventChannel();
// #endif
// console.log('emitName:', data);
eventChannel.emit(emitName, data);
}
// 跳转页面并传参
navigateEmit(url, emitName, data, eventName, callback) {
uni.navigateTo({
url: url,
animationDuration: 400,
success(res) {
res.eventChannel.emit(emitName, data);
},
events: {
[eventName]: function(result) {
// console.log('[eventName]', eventName, result);
return callback(result);
}
}
})
}
}
export default Channel
之后在main.js中导入 并绑到this的原型上
import Channel from "./utils/eventChannel.js"
let chel = new Channel();
Vue.prototype.$channel = chel;
封装了跳转页面并传参方法(a.vue)
// 封装跳转并传值事件
this.$channel.navigateEmit(url, 'tranferParam', res, 'backData', (res) => {
console.log('backData:', res);
})
以及取值方法(b.vue)
// 取值方法
this.$channel.eventOn(this, 'tranferParam', (res) => {
// console.log(res);
this.commonParam.title = res.title;
console.log(res.title);
})
// 及向前页面再次通信的方法
this.$channel.eventEmit(this, 'backData', {
name: '1',
type: 'backData'
})
方法很简单 主要是为了 方便不用每次调用 eventChannel 的时候还要去获取