Dan Tang
Dan Tang

Reputation: 1333

Dynamically loading components in Vue

I have a component that is dynamically loading based on the value of the variable "scene". The problem is I have to import and load all the possible scenes under the components, and I have a lot of different possible components. Is it possible for Vue to just dynamically import the passed in scene, or do I need to import everything at the start?

For other reasons, I would prefer not to use a router for this case.

<component
  :is="scene"
  v-bind="options"
>
</component>

=========

import TitleSceneComponent
  from './scenes/common/TitleSceneComponent.vue';

import NarrationSceneComponent
  from './scenes/common/NarrationSceneComponent.vue';

import ChoiceSceneComponent
  from './scenes/common/ChoiceSceneComponent.vue';

  components: {
    TitleScene: TitleSceneComponent,
    NarrationScene: NarrationSceneComponent,
    ChoiceScene: ChoiceSceneComponent,
  },

Upvotes: 0

Views: 220

Answers (3)

Odd
Odd

Reputation: 1

You can do this:

<component
  :is="sceneComp"
  v-bind="options"
>
</component>

=============================

computed: {
  sceneComp() {
    return () => import(`./scenes/common/${this.scene}Component.vue`);
}

Upvotes: 0

Teej
Teej

Reputation: 12873

I am thinking that you can use a v-if that loads different components depending on the data passed.

<TitleSceneComponent v-if="booleanValueOrCondition" />
<ChoiceSceneComponent v-if="anotherBooleanValueOrCondition" />

This way components can be loaded depending on your conditions.

Upvotes: 1

Joao Alves Marrucho
Joao Alves Marrucho

Reputation: 869

I would use vue router to something like this: https://router.vuejs.org/guide/#html

Upvotes: 0

Related Questions