Search code examples
vue.jsheroicons

Dynamic Heroicons in Vue.js


I assign the heroicon to a variable from my list of menu items.

const navigation = [{ name: 'Dashboard', icon: TemplateIcon, href: '#', current: true }]

Then I try to display the icon.

<li v-for="item in navigation" class="relative px-6 py-3">
    <TemplateIcon class="h-5 w-5" />
    <item.icon class="h-5 w-5" />
</li>

The template icon is only shown once, but should be shown twice. I have already tried this

<{{item.icon}} class="h-5 w-5" />

{{item.icon}}

<svg><path :d="item.icon"></path></svg>

thx for help


Solution

  • You can use Dynamic component approach which is useful to dynamically switch between components.

    This can be achieve by using Vue's <component> element with the special :is attribute.

    Demo :

    new Vue({
      el: '#app',
      data: {
        navigation: [{ icon: 'H3' }]
      }
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <div id="app">
      <div class="container">
        <div v-for="(item, index) in navigation" :key="index">
          <component :is="item.icon">Hello</component>
        </div>
      </div>
    </div>