Reputation: 4132
I'm trying to display a proper icon depending on what type of file it is.
I have this div
that displays either:
an image
or a <v-icon>
component (where {{ext.value}}
is the icon name to display)
<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 () {
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'
How do I make this work? I don't know how to call a method when v-else
branch is true, do I use a method, a computed property?
And how to make sure it uses a generic file icon value: "generic_icon"
(the [0]
in the extensionsList
) for all extensions that do not match any item in the list?
Upvotes: 3
Views: 2777
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