uni-app 跳转页面传参
uni-app Vue2 和 Vue3 页面跳转传参方法
在 uni-app 中,无论是 Vue2 还是 Vue3,页面跳转传参的方式基本一致,主要通过 uni.navigateTo
、uni.redirectTo
等 API 实现。以下是常见的方法:
URL 拼接传参
通过 url
拼接参数,目标页面通过 onLoad
生命周期钩子接收参数。
// 跳转页面并传参
uni.navigateTo({url: '/pages/detail/detail?id=123&name=test'
});
目标页面接收参数:
// 目标页面
export default {onLoad(options) {console.log(options.id); // 123console.log(options.name); // test}
}
Vue2 中使用 Vuex:
// store.js
export default new Vuex.Store({state: {pageParams: {}},mutations: {setPageParams(state, params) {state.pageParams = params;}}
});// 发送页面
this.$store.commit('setPageParams', { id: 123, name: 'test' });
uni.navigateTo({ url: '/pages/detail/detail' });// 目标页面
computed: {pageParams() {return this.$store.state.pageParams;}
}
通过事件通道传参(Vue3 推荐)
- 方法1
Vue3 中可以使用uni.$emit
和uni.$on
实现跨页面通信。
发送参数:
// 发送页面
uni.navigateTo({url: '/pages/detail/detail',success: () => {uni.$emit('updateData', { id: 123, name: 'test' });}
});
接收参数:
// 目标页面
export default {mounted() {uni.$on('updateData', (data) => {console.log(data.id); // 123console.log(data.name); // test});},beforeUnmount() {uni.$off('updateData');}
}
- 方法2
// 发送方uni.navigateTo({url: '/pages/user/order/payment',// 页面跳转传参数(navigateTo 调用成功后)success: (res) => {res.eventChannel.emit('orderInfo', detail)},events: {// 监听b.vue返回的参数successful(data) {console.log(JSON.stringify(data, null, 2))},}});
// 接收方import {getCurrentInstance} from 'vue';const instance = getCurrentInstance();onLoad(() => {const eventChannel = instance.proxy.getOpenerEventChannel();eventChannel.on('orderInfo', (data) => {console.log('data', data)});});
通过本地缓存
对于需要持久化的数据,可以使用 uni.setStorageSync
和 uni.getStorageSync
。
发送参数:
uni.setStorageSync('pageParams', { id: 123, name: 'test' });
uni.navigateTo({ url: '/pages/detail/detail' });
接收参数:
// 目标页面
export default {onLoad() {const params = uni.getStorageSync('pageParams');console.log(params); // { id: 123, name: 'test' }}
}
使用 uni.$once
实现一次性传参
Vue3 中可以通过 uni.$once
实现一次性事件监听。
发送参数:
uni.navigateTo({url: '/pages/detail/detail',success: () => {uni.$emit('onceData', { id: 123, name: 'test' });}
});
接收参数:
// 目标页面
export default {mounted() {uni.$once('onceData', (data) => {console.log(data); // { id: 123, name: 'test' }});}
}
总结
- 简单参数:使用 URL 拼接传参。
- 复杂数据:Vue2 用 Vuex,Vue3 用 事件通道。
- 临时数据:使用
uni.$emit
和uni.$on
。 - 持久化数据:使用本地缓存。
根据具体需求选择合适的方式。