How to render variable components in vue like jsx?

Viewed 1243

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.

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'
    }
  }
}
Related