【问题标题】:Vue Dynamic Component Ordering?Vue 动态组件排序?
【发布时间】:2019-02-13 15:41:33
【问题描述】:

提前感谢您的帮助。

我在一个应用程序中使用了 Vue 的动态组件标签。

https://vuejs.org/v2/guide/components.html#Dynamic-Components

组件列表是通过计算属性提供的,我只是在创建<component /> 元素时对其进行迭代。

<component v-for="component in myComponents" :key="component" is="component />

我遇到的问题是组件是异步加载的,并且某些组件的加载时间有时比其他组件要长。因此,有时组件会按所需顺序加载。

我很好奇是否有人对我如何能够强制组件以所需的顺序显示有任何建议?

【问题讨论】:

    标签: vue.js


    【解决方案1】:

    您可以尝试使用有序计算属性,例如,如果您想按名称对组件进行排序。

    在模板中:

    <component v-for="component in orderedComponents" :key="component" is="component />
    

    在脚本中

    computed: {
      orderedComponents: function () {
        return _.orderBy(this.myComponents, 'name')
      }
    }
    

    这个例子使用的是 Lodash,但是你当然可以按照你想要的方式来订购它。

    您可以查看文档:https://vuejs.org/v2/guide/migration.html#Replacing-the-orderBy-Filter

    【讨论】:

    • 请仔细阅读 OP 的问题:...the components are loaded asynchronously and some components can take longer at times than others to load。所以问题不在于如何简单地订购这些动态组件。
    • 您的回答让我走上了正轨。我最终向我使用的 json 对象添加了一个 order 属性,该对象被添加到了组件列表中。然后我使用您提到的计算属性按该 order 属性进行排序。就像一个魅力......谢谢!
    【解决方案2】:

    是的,您可以通过将 :key 设置为数字来强制执行顺序。

    首先,修改你的 for 循环以使用索引:

    v-for="(index, value) in myComponents"
    

    然后将键设置为索引

    :key="index"
    

    这应该保持顺序完整 - 如果没有,您始终可以先创建占位符,然后在运行时替换它们。

    【讨论】:

      猜你喜欢
      • 2019-04-23
      • 2018-06-12
      • 1970-01-01
      • 2019-07-25
      • 2020-10-24
      • 2020-06-18
      • 2019-02-03
      • 2020-02-20
      • 2015-09-06
      相关资源
      最近更新 更多