Vue3+TS+setup 页面最外层组件的Props参数如果跟URL查询参数相同,并且查询参数不在页面defineProps中声明,会传递到最外层组件的Props中

Vue3+TS+setup 页面最外层组件的Props参数如果跟URL查询参数相同,并且查询参数不在页面defineProps中声明,会传递到最外层组件的Props中

示例代码:

页面: index.vue

<script setup lang="ts">  
</script>  

<template>  
  <SafeArea :insetTop="false" />  
</template>

组件: SafeArea.vue

<script setup lang="ts">  
const props = defineProps<{  insetTop?: boolean; }>();  

console.log("SafeArea", props);  
</script>  

<template>  
  <div>  
    <slot />  
  </div>  
</template>

操作步骤:

访问页面带上查询参数(insetTop):http://xxxx/index?insetTop=20

预期结果:

组件 SafeArea 中 console 正确输出:“SafeArea” {insetTop: false}

实际结果:

组件 SafeArea 中 console 实际输出:“SafeArea” {insetTop: 20}

bug描述:

Vue3+TS+setup 页面最外层组件的Props参数如果跟URL查询参数相同,并且查询参数不在页面defineProps中声明,会传递到最外层组件的Props中


1 回复

这是一个Vue3的特性而非bug。在uni-app中,当URL查询参数与组件props同名时,如果页面组件没有通过defineProps声明这些参数,Vue会自动将这些查询参数作为props传递给页面内的根组件。

解决方案:

  1. 在页面组件中显式声明props:
<script setup lang="ts">
defineProps<{ insetTop?: boolean }>()
</script>
  1. 或者使用路由参数处理:
import { useRoute } from 'vue-router'
const route = useRoute()
const insetTop = route.query.insetTop === 'false' ? false : true
回到顶部