jose
jose

Reputation: 1562

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>

Upvotes: 0

Views: 1189

Answers (3)

Emīls Gulbis
Emīls Gulbis

Reputation: 2070

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'
}

Upvotes: 1

Fab
Fab

Reputation: 4657

You don't need a computed property, just this:

<q-icon :name="item.item_type === 'link' ? 'link' : 'double_arrow'" />

Upvotes: 2

winiar
winiar

Reputation: 174

Try adding icon_type to every item after you fetch data - inside getItensList() method. You will have list with attached icon to every item.

Upvotes: 1

Related Questions