Skip to content

获取页面参数 - defineProps

轻松解析页面参数,兼容扫小程序码、普通二维码参数

背景介绍

应该使用 definedProps 声明页面参数并获取,而非在 onLoad 中获取,如下所示:

js
const options = defineProps({
  id: {type: String, default: ''},
  pid: {type: String, default: ''},
})

console.log(`id=${options.id}`) // id=foo
console.log(`pid=${options.pid}`) // pid=bar

然而,当页面通过扫码二维码或小程序码进入时,页面参数可能会被包装在一个名为 qscene 的参数中。在这种情况下,使用上述方法获取页面参数会变得相对繁琐。

因此,我们提供了 parseSceneOptions 方法用以解析它,可以帮助你处理包装过的参数。

js
let options = defineProps({
  id: {type: String, default: ''},
  pid: {type: String, default: ''},
  // 必须声明 scene 参数,否则无法正常获取
  scene: {type: String, default: ''},
})

options = parseSceneOptions(options)

console.log(`id=${options.id}`) // id=foo
console.log(`pid=${options.pid}`) // pid=bar

相关文档