uni-app 【报Bug】vue3 setup语法通过defineProps获取props为null,使用v2写法能正常获取

uni-app 【报Bug】vue3 setup语法通过defineProps获取props为null,使用v2写法能正常获取

操作步骤:

  • 通过defineProps获取props

预期结果:

  • 可以得到结果

实际结果:

  • 返回null

bug描述:

  • vue3 setup语法通过defineProps获取props为null,使用v2写法能正常获取

Image Image Image Image

4 回复
<script setup> </script>

请提供简单可复现的完整示例(上传附件),方便我们快速排查问题哦。 【bug优先处理规则】https://ask.dcloud.net.cn/article/38139

没看到你在哪里设置的setup啊

uni-app 中使用 Vue 3setup 语法时,如果通过 defineProps 获取 propsnull,而使用 Vue 2 的写法能正常获取,可能是由于以下原因导致的:

1. defineProps 的使用方式不正确

  • Vue 3setup 语法中,defineProps 是一个编译时宏,用于定义组件的 props。确保你正确使用了 defineProps
<script setup>
const props = defineProps({
  myProp: {
    type: String,
    required: true
  }
});

console.log(props.myProp); // 确保这里能正确输出
</script>

2. uni-app 的版本问题

  • uni-appVue 3 的支持可能在不同版本中存在差异。确保你使用的 uni-app 版本支持 Vue 3setup 语法。

  • 你可以尝试更新 uni-app 到最新版本,或者检查是否有相关的 bug 修复。

3. props 传递问题

  • 确保父组件正确传递了 props。如果父组件没有传递 props,或者传递的 props 名称不匹配,defineProps 可能会返回 null
<template>
  <ChildComponent myProp="Hello World" />
</template>

4. setup 上下文问题

  • setup 函数中,props 是通过 defineProps 获取的,而不是通过 setup 的参数获取的。确保你没有混淆 setup 的参数和 defineProps
<script setup>
const props = defineProps({
  myProp: String
});

console.log(props.myProp); // 确保这里能正确输出
</script>

5. Vue 3props 类型定义问题

  • 如果你在 defineProps 中定义了 props 的类型,确保类型定义正确。如果类型不匹配,可能会导致 propsnull
<script setup>
const props = defineProps({
  myProp: {
    type: String,
    required: true
  }
});

console.log(props.myProp); // 确保这里能正确输出
</script>
回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!