uniapp中通过eventChannel
实现页面间通信的方法,这是一种官方推荐的高效传参方式。我来解释下这种方式的完整实现和注意事项:
-
发送页面(父页面) :
javascriptuni.navigateTo({ url: '/pages/detail/detail', success: (res) => { // 通过eventChannel发送数据 res.eventChannel.emit('sendData', { sTypeName: '详情页', sTypeCode: 'detail123' }); } });
-
接收页面(子页面) :
javascriptonLoad(options) { const eventChannel = this.getOpenerEventChannel(); eventChannel.on('sendData', (data) => { console.log('接收到的数据:', data); uni.setNavigationBarTitle({ title: data.sTypeName }); this.params = { type: data.sTypeCode }; }); }
关键点说明:
eventChannel
是uniapp提供的页面间通信机制- 数据是在页面跳转成功后通过
success
回调发送的 - 子页面通过
getOpenerEventChannel()
获取通信通道 - 这种方式适合传递复杂对象,没有URL长度限制
注意事项:
- 确保子页面已加载完成再发送数据(建议放在
onLoad
中接收) - 数据是实时传递的,不是持久化的
- 如果页面是通过
redirectTo
跳转的,则无法使用这种方式 - 建议对事件名使用常量定义,避免拼写错误
在uniapp中通过URL传递参数主要有以下几种方式:
-
基础URL传参方式(适合简单参数):
直接在跳转URL后拼接参数,格式为?key=value&key2=value2
javascriptuni.navigateTo({ url: '/pages/detail/detail?id=123&name=test' });
-
接收参数方式:
在目标页面的onLoad
生命周期函数中获取javascriptonLoad(options) { console.log(options.id); // 输出:123 console.log(options.name); // 输出:test }
-
传递对象参数(需要编码):
javascriptconst params = { id: 123, user: {name: '张三', age: 20} }; uni.navigateTo({ url: '/pages/detail/detail?data=' + encodeURIComponent(JSON.stringify(params)) });
注意事项:
- URL长度有限制(不同浏览器不同,一般不超过2000字符)
- 传递对象时需要先JSON序列化再编码
- 参数会显示在地址栏中,敏感数据不建议用URL传递
- 获取的参数都是字符串类型,需要自行转换
对于复杂数据结构,建议使用eventChannel或Vuex等其它方式传递。
传递方式:
- 全局变量(globalData)
javascript
// App.vue
App({
globalData: {
userInfo: null
}
});
// 页面A
getApp().globalData.userInfo = { name: 'John' };
uni.navigateTo({ url: '/pages/B/B' });
// 页面B
onLoad() {
const userInfo = getApp().globalData.userInfo;
console.log(userInfo); // { name: 'John' }
}
2. Vuex状态管理
Vuex是Vue.js的官方状态管理库,适合管理复杂的全局状态。通过定义state
、mutations
和actions
,可以在不同页面中共享和修改数据2 4。
javascript
// store/index.js
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
sharedData: null
},
mutations: {
updateSharedData(state, payload) {
state.sharedData = payload;
}
}
});
// 页面A
this.$store.commit('updateSharedData', { key: 'value' });
uni.navigateTo({ url: '/pages/B/B' });
// 页面B
onLoad() {
const data = this.$store.state.sharedData;
console.log(data); // { key: 'value' }
}
**3. 本地存储(Storage)**
使用uni.setStorageSync
和uni.getStorageSync
可以将数据存储在本地,适合需要持久化的数据传递1 2
javascript
// 页面A
uni.setStorageSync('param1', 'value1');
uni.navigateTo({ url: '/pages/B/B' });
// 页面B
onLoad() {
const param1 = uni.getStorageSync('param1');
console.log(param1); // 'value1'
}
还有很多自行探索...