Vue3组合式API子组件ref中prop值为undefined问题求助
解决Vue3组合式API中form对象companyId为undefined的问题
核心错误及修复步骤:
错误1:ref调用方式错误
子组件里用new ref(...)是完全错误的写法,ref是Vue提供的函数,不是类,不能用new关键字。修正后:const form = ref({ name: null, companyId: companyId });错误2:解构props丢失响应性
defineProps返回的是响应式对象,直接解构const { companyId } = defineProps(...)会让companyId失去响应性。如果父组件的companyId是异步加载的,子组件初始化时可能还没拿到有效值,导致form里的companyId为undefined。两种修复方案:
- 直接使用props对象访问:
const props = defineProps({ show: { type: Boolean, required: true, default: false }, companyId: { type: Number, required: true } }); const form = ref({ name: null, companyId: props.companyId }); - 用
toRefs保留响应性:import { ref, toRefs } from 'vue'; const props = defineProps({ show: { type: Boolean, required: true, default: false }, companyId: { type: Number, required: true } }); const { companyId } = toRefs(props); const form = ref({ name: null, companyId: companyId.value });
- 直接使用props对象访问:
额外优化:同步props更新
如果父组件的companyId后续可能变化,需要监听其值并同步到form:
import { ref, watch, toRefs } from 'vue'; const props = defineProps({ // ... 原有props配置 }); const { companyId } = toRefs(props); const form = ref({ name: null, companyId: companyId.value }); watch(companyId, (newVal) => { form.value.companyId = newVal; });
内容的提问来源于stack exchange,提问作者Dev 404
相关产品推荐
相关产品推荐

