
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. 页面栈限制 getCurrentPages()返回的是非响应式数据,如需在模板中使用,需手动转为ref或reactive。2. H5 平台差异
H5 端无法通过$page获取完整路径,建议用window.location替代。3. 组件中使用
在组件内获取页面信息时,确保组件已挂载(如在onMounted中调用)。4. 页面生命周期
参数获取优先使用onLoad,其他信息用getCurrentPages()。
根据需求选择合适的方式即可获取当前页面的路由、参数等关键信息。










