Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to render polymorphic list in vue.js?

Consider:

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

In a component, I have an array of 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()]
    }
}

This works, but is not elegant. The typecheck uses a string, where item instanceof B would be idiomatic es6 code. However, this does not work.

What is the idiomatic way of rendering a polymorphic list in vue.js?

like image 503
Ruudjah Avatar asked Jan 28 '26 06:01

Ruudjah


1 Answers

Component keyword must be what you are looking for, like this:

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

Reference from Vue documentation

Here is an example: https://codesandbox.io/s/k2mwrj6w3r

like image 74
cmertayak Avatar answered Jan 29 '26 19:01

cmertayak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!