Vue技术问题:无法多次传入不同参数调用同一组件
问题分析与解决
核心问题1:类型判断不匹配
你定义的testObject2的type为'numeric',但组件内的判断条件写的是getType === 'number',两者不匹配,导致第二个组件的输入框完全没渲染。
核心问题2:Props值同步逻辑缺陷
组件里直接在setup初始化时给newValue赋值props.testProps.value,这只会执行一次,后续如果props发生变化,newValue不会自动更新,需要监听props的变化来同步值。
修改后的组件代码(TestForm.vue)
<!-- eslint-disable vue/no-setup-props-destructure --> <script setup> import { ref, computed, watch } from 'vue'; const newValue = ref(''); const props = defineProps(['testProps']); // 监听props变化,实时同步newValue,immediate确保初始化时也执行 watch(() => props.testProps.value, (newVal) => { newValue.value = newVal; }, { immediate: true }); const getType = computed(() => props.testProps.type); </script> <template> <div> <input v-if="getType === 'string'" type="text" v-model="newValue" /> <!-- 修正判断条件,和传入的type值匹配 --> <input v-if="getType === 'numeric'" type="number" v-model="newValue" /> </div> </template>
主程序无需修改
你的主程序中testObject1和testObject2的定义是正确的,仅修改组件即可解决问题。修改后,两个组件会分别渲染文本输入框和数字输入框,正常显示在页面上。
内容的提问来源于stack exchange,提问作者Samuel
相关产品推荐
相关产品推荐

