如何在Vue中动态加载组件

11
<template>
  <div>
    <v-container fluid id="main">
      <v-card class="white lighten-4 elevation-3">

        <li v-for="stop in stop_name_arr">
          {{stop}}
        </li>

        <direct_bus_travel_time_in_between_stops>
        </direct_bus_travel_time_in_between_stops>

        <direct_bus_travel_distance_in_between_stops>
        </direct_bus_travel_distance_in_between_stops>

      </v-card>
    </v-container>
  </div>
</template>

我有两个组件direct_bus_travel_time_in_between_stopsdirect_bus_travel_distance_in_between_stops,需要在<li v-for="stop in stop_name_arr">{{stop}}</li>完全执行后再加载。

是否有办法在函数内动态添加这些组件,以便在需要加载时加载它们?


什么决定了何时显示其中之一?你可能需要查看条件渲染 - Bert
有一个函数可以加载数组 -> stop_name_arr,以在DOM上反映其内容。 - Shivam Singh
1
v-if="stop_name_arr.length > 0" 可能有效。如果不行,那么在数组加载时设置一个标志或类似的东西。 - Bert
我能否在加载完数组后,从我的脚本动态添加组件? - Shivam Singh
1
Vue通常反映状态。您所建议的是命令式而不是声明式,Vue会抵制以那种方式做事情。 - Bert
搞定了,太棒了!谢谢! - Shivam Singh
1个回答

9
我非常认为你可以使用元component标记,该标记在传递给is属性的组件中异步加载给定组件。以下是代码: <component is="direct_bus_travel_time_in_between_stops" > </component> <component is="direct_bus_travel_time_in_between_stops" > </component> 您可以添加此标记中的函数/事件,以使其条件加载。 我认为这个链接会有帮助:https://v2.vuejs.org/v2/guide/components.html#Dynamic-Components, 其中描述了绑定要动态使用的组件。
希望我的方法对您有用!
更新:此答案是针对Vue 2.x版本提供的。我不知道Vue 3.x版本并且没有阅读3.x文档。您可以随时提交编辑草稿以获得Vue 3.x兼容的解决方案。谢谢!

1
这在Vue 3中也适用。https://vuejs.org/guide/essentials/component-basics.html#dynamic-components 谢谢你的提示! - Daantje

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接