Home > Software design >  Use custom vuetify icon in template by it name from variable
Use custom vuetify icon in template by it name from variable

Time:02-21

I'm trying to render custom vuetify icons in list with next template:

<template v-for="item in items">
    <v-list nav :key="item.name">
        <v-list-item link :to="item.to">
            <v-list-item-icon>
                <v-icon color="white">{{$vuetify.icons.values[item.icon]}}</v-icon>
            </v-list-item-icon>
            <v-list-item-title>{{item.name}}</v-list-item-title>
        </v-list-item>
    </v-list>
</template>

Script:

<script lang="ts">
...
export default class Menu extends Vue {

items: Array<any> = [
    {
        name: "Home",
        to: "/Home",
        icon: "test1"
    },
    {
        name: "Contacts",
        to: "/Contacts",
        icon: 'test2'
    }   
]}
</script>

Registered icons in vuetify.ts

Vue.use(Vuetify, {
    icons: {
        iconfont: "mdi",
    },
    values: {
        test1: '...svg'
        test2: '...svg'
    }
});

My first question is when I use custom icon with $vuetify.icons.test1 it's working correctly. But what should I need to do if I'm getting this value dynamically. And second one is there any way to use it as normal icon, example:

<v-icon>test1</v-icon>

CodePudding user response:

The template syntax for custom icons assumes that the icon path is a string. You can use string interpolation to define dynamic icons.

<v-icon color="white">{{ `$vuetify.icons.${item.icon}` }}</v-icon>

Concerning, the second question, there is a shorthand for custom icons:

<v-icon color="white">$test1</v-icon>

The dynamic version will look like:

<v-icon color="white">{{ `$${item.icon}` }}</v-icon>

Also, make note that you don't need to specify values for custom icons. All icons (built in and custom) are pulled into one icons object.

  • Related