在这里跟大家分享下,本人在开发小程序的过程中,获取当前小程序路径和参数的用法,以及遇到的一些坑。
基本用法
----获取路径
var pages = getCurrentPages(); //获取加载的页面
var currentPage = pages[pages.length - 1] //获取当前页面的对象
var url = currentPage.route //获取页面url
console.log(url); //打印url
----获取路径的参数
方法一
var pages = getCurrentPages(); //获取加载的页面
var currentPage = pages[pages.length - 1] //获取当前页面的对象
const options = currentPage.options //获取当前页面的参数
console.log(options); //打印当前页面的参数
方法二:需要在onLoad中使用
onLoad: function (options) {
console.log(options) //打印当前页面的参数
}
防坑指南
- currentPage is not defined;
opyions is not defined;
不细心的我少写了前两句,以为参数是可以直接引用的
var pages = getCurrentPages(); //前两句不要忘记写
var currentPage = pages[pages.length - 1] //前两句不要忘记写
const options = currentPage.options
console.log(options);
- 注意this的使用,有时需要定义全局变量来调用
onLoad: function (options) {
var that = this;
that.setData({
id: 1,
})
}
本文介绍了在开发小程序时如何获取当前页面路径和参数,包括两种方法,并特别提醒开发者注意可能遇到的错误,如currentPage未定义、options未定义以及this的使用问题,强调了细心和正确引用全局变量的重要性。

被折叠的 条评论
为什么被折叠?



