Search code examples
vue.jsiconsquasar

Change the item's icon dynamically according to the value received in response


I need to change the item's icon dynamically according to the value received in the server's response.

I'm trying to do this with a computed property, but I'm not getting the item_type value sent in the response.

I appreciate ideas on how to make this work?

<template>
<div class="q-pa-md">
    <q-list>
        <q-item 
            clickable 
            v-for="(item, index) in itens" 
            :key="item.id_item" 
            :id="index" >

            <q-item-section avatar>
                <q-icon :name="iconType" />
            </q-item-section>

            <q-item-section>
                <q-item-label>{{ item.item_name }}</q-item-label>
            </q-item-section>

        </q-item>
    </q-list>
    </div>
</template>

<script>

export default {
    data () {
        return {
            itens: [
              //  id_item:''
              //  item_name:'',
              //  item_type:''
            ]
        }
    },

    computed : {
        iconType(){
            let type = this.itens.item_type; //does not work

            if(type === 'link'){
               return "link"
            }else{
               return 'double_arrow'
            }
        }
    },

    mounted: {
        this.getItensList();
    },

    methods: {
        getItensList(id){            
             this.$axios.get(`/itenslist`)                
            .then(response => {              
              if (response.data.success) {
                  this.itens = response.data.itens
              } else {
              }
            })
            .catch(error => {         
            });
        },
    }
}
</script>

Solution

  • You can't use computed properties like this, instead you can create method

    iconType(item){
      let type = item.item_type
    
      if(type === 'link'){
        return "link"
      } else {
        return 'double_arrow'
      }
    }
    

    and use it like <q-icon :name="iconType(item)" />

    for cleaner code you may try this approach

    iconType(item) {
      return {
        link: 'link',
        otherType: 'otherIcon'
      }[item.itemType] || 'double_arrow'
    }