Skip to content

获取页面路由

获取当前页面完整的信息

js
const pages = getCurrentPages(); // 获取当前页面栈
const currentPage = pages[pages.length - 1]; // 当前页面

console.log('当前页面路径:', currentPage.route); // 如 "pages/index/index"
console.log('页面参数:', currentPage.options); // 路由参数
console.log('页面实例:', currentPage); // 完整页面实例
const pages = getCurrentPages(); // 获取当前页面栈
const currentPage = pages[pages.length - 1]; // 当前页面

console.log('当前页面路径:', currentPage.route); // 如 "pages/index/index"
console.log('页面参数:', currentPage.options); // 路由参数
console.log('页面实例:', currentPage); // 完整页面实例

页面导航守卫

js
// 在页面onLoad生命周期中判断
onLoad() {
  const currentRoute = this.$route.fullPath; // vue-router方式
  // 或使用原生方式
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  
  if (currentPage.route === 'pages/login/index') {
    // 登录页逻辑
  }
}
// 在页面onLoad生命周期中判断
onLoad() {
  const currentRoute = this.$route.fullPath; // vue-router方式
  // 或使用原生方式
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  
  if (currentPage.route === 'pages/login/index') {
    // 登录页逻辑
  }
}

不同平台有着差异

js
// 在小程序环境中
const pages = getCurrentPages();
const currentPage = pages[pages.length - 1];
console.log(currentPage.route); // 小程序特有属性

// 在H5环境中
const route = this.$route.path; // 使用vue-router方式
// 在小程序环境中
const pages = getCurrentPages();
const currentPage = pages[pages.length - 1];
console.log(currentPage.route); // 小程序特有属性

// 在H5环境中
const route = this.$route.path; // 使用vue-router方式

程序员小洛文档