Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to render variable components in vue like jsx?

In jsx we can store components in variables like const comp=<p>Hello</p> and then we can put these variables anywhere, choosing witch component to render.

I was wondering if there is a similar thing in vue. If I had a template like:

<template>
  <variable-comp />
</template>

I would like to change what variable-comp is dynamically. I'm aware of v-if and v-for but that's not the same thing.

like image 465
Gabriel Machado Avatar asked Jan 25 '26 23:01

Gabriel Machado


1 Answers

vue uses this syntax for dynamic components

<component v-bind:is=”currentComponent”/>

where 'currentComponent' is the name (string) of component.

i.e.

<template>
  <component v-bind:is=”currentComponent”/>
</template>
import CompA from './CompA.vue'
import CompB from './CompB.vue'
export default {
  components: {
    CompA,
    CompB
  },
  data() {
    isA: true
  },
  computed: {
    currentComponent() {
      return isA ? 'CompA' : 'CompB'
    }
  }
}
like image 186
steven Avatar answered Jan 28 '26 14:01

steven



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!