Un1
Un1

Reputation: 4132

How to create a Vue method that dynamically chooses an icon from a list for a corresponding extension?

I'm trying to display a proper icon depending on what type of file it is.

I have this div that displays either:

div

<div>
  <img v-if="isImg(props.item.path)" :src="props.item.path">
  <v-icon v-else v-for="ext in extensionsList" :key="ext.id">
    {{ext.value}}   <=== should put a corresponding value if matches any extension
  </v-icon>
</div>

data

data () {
  return {
    extensionsList: [
      {value: "generic_icon", extension: ['.ini', '.dll']},
      {value: "code_icon", extension: ['.json', '.py']},
      {value: "text_icon", extension: '.txt'}
    ]
  }
}

I can get a file extension by using this method:

getExtension (value) {
  return path.extname(value)
}

props.item is an object containing file properties so I pass that as the input into path.extname() and it returns something like: '.ini', or '.jpg'


Upvotes: 3

Views: 2777

Answers (1)

thanksd
thanksd

Reputation: 55664

I would just make a method to return the associated icon:

methods: {
  getIcon(ext) {
    let icon = this.extensionsList.find((item) => {
      let { extension } = item;
      if (Array.isArray(extension)) {
        return extension.includes(ext);
      } else if (typeof extension === 'string') {
        return extension === ext;
      }
    }) || {};

    return icon.value || "generic_icon";
  }
}

And then call that in the template like so:

<div>
  <img v-if="isImg(props.item.path)" :src="props.item.path">
  <v-icon v-else>
    {{ getIcon(getExtension(props.item.path)) }}
  </v-icon>
</div>

Upvotes: 4

Related Questions