uniapp页面间传参的方法

uniapp中,常见的页面传参方式有以下几种:

  1. URL传参

可以在跳转页面时,在url中添加参数,通过在目标页面的onLoad函数中的options参数获取传递的参数。示例代码如下:

在源页面中:

复制代码
uni.navigateTo({
    url: '/pages/targetPage/index?id=123&name=test'
});

在目标页面中:

复制代码
onLoad: function(options) {
    console.log(options.id);
    console.log(options.name);
}
  1. Vuex状态管理

可以在源页面设置一个state,然后在目标页面中获取该state的值。示例代码如下:

在源页面中:

复制代码
this.$store.state.id = 123;
this.$store.state.name = 'test';
uni.navigateTo({
    url: '/pages/targetPage/index'
});

在目标页面中:

复制代码
computed: {
    id: function() {
        return this.$store.state.id;
    },
    name: function() {
        return this.$store.state.name;
    }
}
  1. uni传参

可以在源页面使用uni对象的navigateTo方法传参,在目标页面中使用uni对象的getOpenerEventChannel方法获取传递的参数。示例代码如下:

在源页面中:

复制代码
uni.navigateTo({
    url: '/pages/targetPage/index',
    success: function(res) {
        var channel = uni.getOpenerEventChannel();
        channel.emit('passData', {id: 123, name: 'test'});
    }
});

在目标页面中:

复制代码
onLoad: function() {
    var _this = this;
    var channel = uni.getOpenerEventChannel();
    channel.on('passData', function(data) {
        _this.id = data.id;
        _this.name = data.name;
    });
}

其中,emit方法用于向目标页面传递数据,on方法用于监听由emit方法传递过来的数据。

相关推荐
人工智能训练师12 小时前
Ubuntu22.04如何安装新版本的Node.js和npm
linux·运维·前端·人工智能·ubuntu·npm·node.js
Seveny0712 小时前
pnpm相对于npm,yarn的优势
前端·npm·node.js
yddddddy13 小时前
css的基本知识
前端·css
昔人'13 小时前
css `lh`单位
前端·css
Nan_Shu_61415 小时前
Web前端面试题(2)
前端
知识分享小能手15 小时前
React学习教程,从入门到精通,React 组件核心语法知识点详解(类组件体系)(19)
前端·javascript·vue.js·学习·react.js·react·anti-design-vue
00后程序员张15 小时前
详细解析苹果iOS应用上架到App Store的完整步骤与指南
android·ios·小程序·https·uni-app·iphone·webview
蚂蚁RichLab前端团队16 小时前
🚀🚀🚀 RichLab - 花呗前端团队招贤纳士 - 【转岗/内推/社招】
前端·javascript·人工智能
孩子 你要相信光16 小时前
css之一个元素可以同时应用多个动画效果
前端·css
huangql52016 小时前
npm 发布流程——从创建组件到发布到 npm 仓库
前端·npm·node.js