微信小程序 如何获取页面路径
作者:互联网
在微信小程序中,可以通过 getCurrentPages()
方法获取当前页面的路径。以下是具体的使用方法:
获取当前页面的路径
-
使用
getCurrentPages()
方法: 该方法返回当前页面栈的数组,最后一个元素就是当前页面。const pages = getCurrentPages(); // 获取页面栈 const currentPage = pages[pages.length - 1]; // 获取当前页面 const currentPath = currentPage.route; // 获取当前页面路径 console.log('当前页面路径:', currentPath);
JavaScript
示例
将上述代码放在页面的 JS 文件中的某个函数中,例如在 onLoad
函数中:
Page({
onl oad: function () {
const pages = getCurrentPages(); // 获取页面栈
const currentPage = pages[pages.length - 1]; // 获取当前页面
const currentPath = currentPage.route; // 获取当前页面路径
console.log('当前页面路径:', currentPath);
}
});
JavaScript
注意事项
route
属性返回的是页面的相对路径,不包含.html
后缀。- 如果需要页面的完整路径(例如,加上小程序的路径前缀),可以手动拼接。
标签: 来源: