【问题标题】:Dynamically loading components in VueVue中动态加载组件
【发布时间】:2020-01-21 08:00:52
【问题描述】:

我有一个基于变量“场景”的值动态加载的组件。问题是我必须在组件下导入和加载所有可能的场景,而且我有很多不同的可能组件。 Vue 是否可以只动态导入传入的场景,还是我需要在开始时导入所有内容?

出于其他原因,我不想在这种情况下使用路由器。

<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,
  },

【问题讨论】:

    标签: vue.js


    【解决方案1】:

    你可以这样做:

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

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

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

    【讨论】:

      【解决方案2】:

      我认为您可以使用 v-if 根据传递的数据加载不同的组件。

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

      这种方式可以根据您的条件加载组件。

      【讨论】:

        【解决方案3】:

        我会使用 vue 路由器来做这样的事情:https://router.vuejs.org/guide/#html

        【讨论】:

        • 我不想在这种情况下使用路由器,因为我希望这个组件能够处理不同的状态,并根据需要简单地更改组件。
        猜你喜欢
        • 2018-07-08
        • 2019-06-30
        • 2018-01-09
        • 2018-05-22
        • 2019-07-31
        • 1970-01-01
        • 1970-01-01
        • 2020-09-14
        • 2020-12-21
        相关资源
        最近更新 更多