uniapp vue3 setup写法如何获取页面参数
在uniapp中使用vue3的setup语法,如何获取页面传递的参数?比如从A页面跳转到B页面时带上了id参数,在B页面的setup中应该怎么接收这个参数?试过用onLoad生命周期钩子,但在setup里好像不生效,求具体写法示例。
2 回复
在uniapp的vue3 setup中,可以通过以下方式获取页面参数:
- onLoad生命周期:
onLoad((options) => {
console.log(options.id) // 获取参数
})
- 路由实例:
import { getCurrentInstance } from 'vue'
const instance = getCurrentInstance()
const query = instance.proxy.$route.query
推荐使用onLoad方式,更符合uniapp规范。
在 UniApp 中使用 Vue 3 的 setup
语法获取页面参数,可以通过以下方法实现:
1. 使用 onLoad
生命周期钩子
在 setup
函数中,通过 onLoad
钩子获取页面参数。示例代码如下:
import { onLoad } from '@dcloudio/uni-app';
export default {
setup() {
onLoad((options) => {
// options 包含页面传递的参数
console.log('页面参数:', options);
// 例如获取 id 参数
const id = options.id;
});
}
};
2. 使用路由实例(适用于需要动态响应参数的情况)
通过 getCurrentInstance
获取当前页面实例,再访问参数:
import { getCurrentInstance } from 'vue';
export default {
setup() {
const instance = getCurrentInstance();
const options = instance.proxy.$page.options;
console.log('页面参数:', options);
}
};
注意事项:
- 参数类型:所有参数均为字符串类型,需自行转换(如
Number(options.id)
)。 - 适用场景:
onLoad
适用于页面初始化时获取参数;路由实例方法可用于响应参数变化(如页面栈更新)。
以上方法简单高效,适用于 UniApp 的 Vue 3 项目。