uniapp vue3模式获取当前页面信息

www.jswusn.com Other 2025-06-18 09:41:23 3次浏览

1. uniapp vue3模式获取当前页面信息

UniApp 的 Vue 3 模式中,获取当前页面信息(如路由、参数等)主要有以下几种方式:

1. 使用 getCurrentPages() 方法

这是最常用的方式,可获取当前页面栈和页面实例:

// 在页面或组件的 setup 中
import { getCurrentInstance } from'vue';

exportdefault {
setup() {
    // 获取页面栈数组(最后一项是当前页面)
    const pages = getCurrentPages();
    const currentPage = pages[pages.length - 1];
    
    // 获取页面信息
    const route = currentPage.route; // 页面路径(如 "pages/index/index")
    const options = currentPage.options; // 页面参数对象
    const fullPath = currentPage.$page.fullPath; // 完整路径(含参数)
    
    console.log('当前页面路径:', route);
    console.log('页面参数:', options);
    console.log('完整路径:', fullPath);
    
    return { route, options };
  }
}


2. 通过页面生命周期 onLoad 获取参数

在页面加载时直接获取传递的参数:

<script setup>
import { onLoad } from '@dcloudio/uni-app';

onLoad((options) => {
  // options 是页面传递的参数对象
  console.log('页面参数:', options);
});
</script>

3. 使用 Vue Router 风格(需配置)

如果项目启用了 uni-simple-router 等路由库,可使用路由 API:

import { useRoute } from 'uni-simple-router';

export default {
  setup() {
    const route = useRoute();
    console.log('当前路径:', route.path);
    console.log('参数:', route.query);
  }
}


注意:UniApp 默认不支持 Vue Router,需手动集成第三方路由库。

4. 获取当前页面实例(Vue 3 方式)

通过 Vue 的 getCurrentInstance 获取页面上下文:

import { getCurrentInstance } from 'vue';

export default {
  setup() {
    const instance = getCurrentInstance();
    const pageInstance = instance.proxy.$scope; // 小程序页面实例
    const route = pageInstance.route; // 页面路径
    
    console.log('页面实例:', pageInstance);
  }
}



完整示例代码

<script setup>
import { ref, onMounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app';

// 方法1:通过 onLoad 获取参数
onLoad((options) => {
  console.log('onLoad 参数:', options);
});

// 方法2:通过 getCurrentPages 获取信息
const pageInfo = ref({});
onMounted(() => {
  const pages = getCurrentPages();
  if (pages.length) {
    const currentPage = pages[pages.length - 1];
    pageInfo.value = {
      route: currentPage.route,
      params: currentPage.options,
      fullPath: currentPage.$page?.fullPath || ''
    };
  }
});
</script>

<template>
  <view>
    <text>页面路径:{{ pageInfo.route }}</text>
    <text>页面参数:{{ JSON.stringify(pageInfo.params) }}</text>
  </view>
</template>

注意事项

  1. 1. 页面栈限制
    getCurrentPages() 返回的是非响应式数据,如需在模板中使用,需手动转为 ref 或 reactive
  2. 2. H5 平台差异
    H5 端无法通过 $page 获取完整路径,建议用 window.location 替代。
  3. 3. 组件中使用
    在组件内获取页面信息时,确保组件已挂载(如在 onMounted 中调用)。
  4. 4. 页面生命周期
    参数获取优先使用 onLoad,其他信息用 getCurrentPages()

根据需求选择合适的方式即可获取当前页面的路由、参数等关键信息。


上一篇:没有了!

Other

下一篇:vue-office 预览pdf 如何 显示滚动条

技术分享

苏南名片

  • 联系人:吴经理
  • 电话:152-1887-1916
  • 邮箱:message@jswusn.com
  • 地址:江苏省苏州市相城区

热门文章

Copyright © 2018-2025 jswusn.com 版权所有

技术支持:苏州网站建设  苏ICP备18036849号