vue3实现动态组件+动态参数

381 阅读1分钟

思路

在 Vue 3 中使用 component 创建动态组件时,传递给每个动态组件的参数可以根据组件的不同而变化。可以使用 v-bind 动态地绑定属性,并根据组件类型传递不同的 props。

<template>
  <component :is="currentComponent" v-bind="currentProps"></component>
</template>

<script setup>
import ComponentA from './ComponentA.vue'
import ComponentB from './ComponentB.vue'

// 动态组件和其对应的 props
const currentComponent = ref('ComponentA') // 动态切换的组件
const currentProps = ref({ propA: 'Value A' }) // 对应的 props

// 根据组件切换 props
const switchComponent = () => {
  if (currentComponent.value === 'ComponentA') {
    currentComponent.value = 'ComponentB'
    currentProps.value = { propB: 'Value B', anotherProp: 42 }
  } else {
    currentComponent.value = 'ComponentA'
    currentProps.value = { propA: 'Value A' }
  }
}
</script>

在这个例子中,v-bind="currentProps" 会将 currentProps 中的所有属性作为动态组件的 props 传递,且每个组件可以根据当前组件的类型使用不同的 props。