| 标题 | uniapp获取当前path | |||||||||||||||||||||||||||||||||||||||||||||
| 内容 | 在使用 UniApp 进行开发时,开发者常常需要获取当前页面的路径(path),以便进行页面跳转、数据传递或路由管理。以下是几种常见的获取当前 path 的方法总结。 一、获取当前 path 的常用方式
二、具体实现方式 1. 使用 `getCurrentPages()` ```javascript const pages = getCurrentPages(); const currentPage = pages[pages.length - 1]; const path = currentPage.route; console.log(path); ``` - 适用场景:适用于页面跳转后的路径获取。 - 注意事项:该方法返回的是页面栈中的最后一个页面对象,因此可以准确获取当前页面的路径。 2. 使用本地存储记录路径 在页面跳转前将当前路径保存到本地存储: ```javascript uni.setStorageSync('uni_route', this.$router.currentRoute.path); ``` 在目标页面中读取: ```javascript const path = uni.getStorageSync('uni_route'); console.log(path); ``` - 适用场景:适用于跨页面传递路径信息。 - 注意事项:需要手动维护存储内容,避免数据过期。 3. 使用 `uView` 路由工具 如果项目中使用了 `uView` 框架,可以通过以下方式获取路径: ```javascript import { route } from '@/utils/router'; console.log(route.path); ``` - 适用场景:适用于已集成 `uView` 的项目。 - 注意事项:需确保 `uView` 已正确引入并配置。 4. Vue Router(仅限 H5) 在 H5 环境下,如果使用了 Vue Router,可以直接通过 `$router.currentRoute.path` 获取当前路径: ```javascript console.log(this.$router.currentRoute.path); ``` - 适用场景:适用于 H5 环境下的 uni-app 项目。 - 注意事项:不适用于小程序环境。 三、总结
在实际开发中,建议优先使用 `getCurrentPages()` 获取当前页面路径,简单且通用。若涉及复杂路由逻辑,可结合 `uView` 或 Vue Router 提供的工具进行扩展。 | |||||||||||||||||||||||||||||||||||||||||||||
| 随便看 |