页面使用defineProps定义了页面传参在uni-app微信小程序中没有传递的参数会被定义为空字符串若将对应参数作为props传递给组件就会导致组件的props默认值失效

页面使用defineProps定义了页面传参在uni-app微信小程序中没有传递的参数会被定义为空字符串若将对应参数作为props传递给组件就会导致组件的props默认值失效

产品分类:

uniapp/小程序/微信

示例代码:

页面代码

<template>  
    <view>  
        <testProps :text="text" />  
        <testProps :text="123" />  
        <testProps text="456" />  
    </view>  
</template>  

<script setup lang="ts">  
    import testProps from '@/components/testProps.vue'  
    const props = defineProps({  
        text:String  
    })  
</script>

组件代码

<template>  
    <view class="">  
        <text>text:{{text}}</text>  
    </view>  
</template>  

<script setup lang="ts">  
    const props = defineProps({  
        text:{  
            type:[String,Number],  
            default:1  
        }  
    })  
</script>

附件亦有代码可供复现


## 操作步骤:
页面使用`defineProps`定义页面传参,组件的`props`对应参数为`string`或`string`与`number`类型,`props`的默认值就会失效。

## 预期结果:
应为空值,不应为空字符串。

## 实际结果:
实际获取到的`props`是空字符串。

## bug描述:
页面使用`defineProps`定义了页面传参,由于页面传参只能是`string`类型,没有传递的参数会被定义为空字符串,若将对应参数作为`props`传递给组件,就会导致组件的`props`默认值失效,因为拿到的对应`props`实际为空字符串,不算空值。

更多关于页面使用defineProps定义了页面传参在uni-app微信小程序中没有传递的参数会被定义为空字符串若将对应参数作为props传递给组件就会导致组件的props默认值失效的实战教程也可以访问 https://www.itying.com/category-93-b0.html

10 回复

没太理解你的意思 子组件内加个逻辑运算符 试试呢 <template>
<view class="">
<text>text:{{text || ‘1’}}</text>
</view>
</template>

<script setup lang="ts"> const props = defineProps({ text:{ type:[String,Number], default:1 } }) </script>

更多关于页面使用defineProps定义了页面传参在uni-app微信小程序中没有传递的参数会被定义为空字符串若将对应参数作为props传递给组件就会导致组件的props默认值失效的实战教程也可以访问 https://www.itying.com/category-93-b0.html


那props的default意义何在?

回复 半驯之马: 当然有用啊 但是因为 Vue 的 props 设计机制是:当父组件显式传递任何值(包括空字符串 null 0 false )时 Vue 会认为这是一个有效的显式传递值 然后子组件的默认值就会被覆盖 所以你组件内显示的是空字符串

回复 半驯之马: 空值时你可以不传text 或者 传入undefined 这样就会显示出默认值了 再或者就在子组件内加上运算符判断默认值

回复 爱豆豆: 我的问题不就是因为uni的这个机制,当页面使用defineProps来代替onLoad获取页面参数时,所定义的页面参数如果没传,此时对应参数是一个空字符串,这个问题就会导致当拿这个参数传递给组件时,因为是空字符串,所以不会触发组件的defineProps中的默认参数,你明白了吗,你拿我实例代码去复现

回复 爱豆豆: 我在页面中写了const props = defineProps({ text:String }) ,这个props就是页面的参数合集,当我访问这个页面而不传递text参数时,这个页面中props的text是一个空字符串,我拿这个props的text传递给testProps 组件的text,此时testProps拿到的text就是空字符串,导致testProps中props 定义的text默认值为1不生效,这样讲够清晰吗

回复 半驯之马: 你看下我上面的回复

回复 爱豆豆: 我知道怎么解决这个问题,我现在说的这个问题是不是一个bug?没有传递的参数为什么拿到的是空字符串,这本来就不合理

官方是没人了吗?连着两个必复现的bug都没人回应

这是一个典型的 uni-app 小程序页面传参类型转换问题。

在微信小程序中,页面参数确实只能传递字符串类型。当页面使用 defineProps 接收参数时,未传递的参数会被设置为空字符串而非 undefined,这就导致了组件 props 默认值失效。

问题分析:

  • 页面级 defineProps 接收到的空参数是 ''(空字符串)
  • 组件级 defineProps 的默认值只在 undefined 时生效
  • 空字符串 '' 不等于 undefined,因此默认值不触发

解决方案: 在页面层对参数进行转换处理:

<script setup lang="ts">
import testProps from '@/components/testProps.vue'

const props = defineProps({
    text: String
})

// 转换空字符串为 undefined
const normalizedText = computed(() => 
    props.text === '' ? undefined : props.text
)
</script>

<template>
    <view>
        <testProps :text="normalizedText" />
    </view>
</template>
回到顶部