You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VueJS中如何根据父组件Props渲染指定子组件

动态根据Prop切换嵌套组件的实现方案

核心思路

通过计算属性监听父组件传入的Prop值,动态返回要渲染的组件对象,再结合<component :is>语法实现组件切换。

具体实现(分Vue版本)

Vue 3(Composition API)

<script setup>
// 导入需要切换的两个按钮组件
import ButtonB from './ButtonB.vue' // Prop值为'b'时渲染的组件
import ButtonOther from './ButtonOther.vue' // 其他值时渲染的组件

// 定义接收父组件的Prop
const props = defineProps({
  btnType: {
    type: String,
    default: '' // 可设置默认值
  }
})

// 计算属性动态返回目标组件
const targetComponent = computed(() => {
  return props.btnType === 'b' ? ButtonB : ButtonOther
})
</script>

<template>
  <!-- 绑定动态组件 -->
  <component :is="targetComponent" />
</template>

Vue 2(Options API)

<template>
  <component :is="targetComponent" />
</template>

<script>
import ButtonB from './ButtonB.vue'
import ButtonOther from './ButtonOther.vue'

export default {
  props: {
    btnType: {
      type: String,
      default: ''
    }
  },
  computed: {
    targetComponent() {
      return this.btnType === 'b' ? ButtonB : ButtonOther
    }
  }
}
</script>

父组件调用示例

<template>
  <!-- 传入'b'渲染ButtonB -->
  <ButtonSelector btnType="b" />
  <!-- 传入其他值渲染ButtonOther -->
  <ButtonSelector btnType="a" />
</template>

<script setup>
import ButtonSelector from './ButtonSelector.vue'
</script>

补充说明

  • 直接使用导入的组件对象而非字符串,无需额外注册全局组件,更安全可靠;
  • 若需用字符串形式指定组件名,需确保组件已在当前组件局部注册或全局注册,此时计算属性返回对应字符串即可(比如return props.btnType === 'b' ? 'ButtonB' : 'ButtonOther')。

内容的提问来源于stack exchange,提问作者Death111

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 07:35:02