【问题标题】:How to render polymorphic list in vue.js?如何在 vue.js 中渲染多态列表?
【发布时间】:2018-02-11 20:01:05
【问题描述】:

考虑:

class X {}
class B extends X {}
class C extends X {}

在一个组件中,我有一个 X 数组:

<template>
    <ul>
        <li v-for="item in items">
            <a-view v-if="item.constructor.name === 'A'"></a-view>
            <b-view v-if="item.constructor.name === 'B'"></b-view>
        </li>
    </ul>
</template>

export default {
    ...
data() {
    return {
        items: [new A(), new B()]
    }
}

这可行,但并不优雅。类型检查使用字符串,其中 item instanceof B 将是惯用的 es6 代码。但是,这不起作用。

在 vue.js 中渲染多态列表的惯用方式是什么?

【问题讨论】:

    标签: javascript ecmascript-6 polymorphism vuejs2


    【解决方案1】:

    Component关键字一定是你要找的,像这样:

    <li v-for="item in items">
      <component v-bind:is="item"></component>
    <li>
    

    Reference from Vue documentation

    这里是一个例子:https://codesandbox.io/s/k2mwrj6w3r

    【讨论】:

    • 这些文档让我很困惑。我使用&lt;component v-bind:is="B"&gt;&lt;/component&gt; 尝试了您的解决方案,但这不起作用。
    • @Ruudjah 它不应该是“B”,而是我上面写的“项目”。它将渲染被引用的组件。在您的 for 循环示例中,它将首先渲染 A 组件,然后是 B 组件。
    • @Ruudjah 我在答案中添加了一个示例代码。查看 App.vue、ComponentA.vue 和 ComponentB.vue。希望对您有所帮助。
    • @cmertayak 完美!
    猜你喜欢
    • 2019-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-17
    • 2021-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多