Using Vue.js to dynamically render content in the DOM based on file extensions

Previously, I used Vue.js to load various text and media data from an object into the DOM. Sometimes it was images, other times videos. To handle this, I came up with the following solution:

<img id="example-image" :src="item.media" :alt="item.image + 'example pic'" @error="loadVideo()">
<video id="example-video">
<source :src="item.media" type="video/mp4">
</video>

This way, if the content is an image, it will display as an image. If it's a video (which would fail to load in an IMG tag), it triggers a method to hide the image and show the video instead.

Unfortunately, this approach is not optimal as it works well in Chrome but has issues in Safari where the content won't display until fully downloaded on the client side – leading to unnecessary bandwidth usage.

I thought about checking the file extension using a method and dynamically loading the content with the appropriate HTML tag based on that. For example:

getFileExtension(filename) {
return filename.slice((filename.lastIndexOf(".") - 1 >>> 0) + 2);
}

If anyone has a better idea or suggestion, I would greatly appreciate it. Thank you very much.

Answer №1

If you only have the file name available, then your best option is to determine whether to display an image or video based on the file extension (as previously suggested).

Consider implementing something along these lines:

<video v-if="isVideo(item.file)">
  <source :src="item.file" type="video/mp4">
</video>
<img v-else :src="item.file">
methods: {
  isVideo(filename) {
    return /\.mp4$/i.test(filename);
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieving information from two MongoDB collections (with filtering on _id) within a Meteor application

I've been facing an issue with my Meteor application for quite some time now. I'm creating a platform where users can sign up for groups, upload images, and assign specific tags to their images. The Tags collection holds unique identifiers (_id) ...

What is the best way to develop a card stack swiper similar to Tinder using React?

After experimenting with various packages, I found that none were satisfactory for creating a customizable card swiper. As a result, I am now considering developing my own solution. What would be the best approach for adding animations, enabling draggable ...

After selecting a value in a form created with Rails 4.0, CoffeeScript fails to trigger the alert message

When working with a :quote resource, I want to trigger a function when the value of the first field (a collection_select) is changed. Additionally, my code includes fields_for :bikes, which represents a relationship where bikes has_many quotes. Below is t ...

Exploring Vue Components Through the Global Scope

Is it feasible to retrieve an instantiated Vue.js component object from the global JavaScript scope with Vue.js, or are these objects encapsulated within Vue's internals? For instance, when I have code defining a component like this: Vue.component(&a ...

Distinctive titles for JavaScript constructors/prototypes compared to classes

When working with JavaScript ES6, classes allow us to write code like this: class RectangularShape { constructor(height, width) { this.height = height; this.width = width; } getArea() { return this.height * this.width } static some ...

Swap out the HTML tags for some Angular 6 text!

I have a specific word in my code that I want to change using an HTML tag and apply the style with the themecolor class. <h2 class="mb-30" [innerHTML]="main_title"></h2> Here is a preview of the result: This is some sample text. I need to ...

Working with external data in D3.js involves loading and manipulating datasets efficiently

As a newcomer to D3.js, I have been exploring various tutorials and exercises to familiarize myself with it. My primary goal with D3 is to load external data, typically in JSON format, and create interactive charts based on that data. You can find the bas ...

Fetching the second item within an object using JavaScript

I am trying to retrieve the data from the last month of an API, but I want to avoid hard-coding the date like this: const data = [data.data['Monthly Time Series']['2021-11-30']]. I need a way to dynamically access the 2nd object without ...

Struggling with passing values to onClickHandler because of MUI

I'm looking to create a category navigation menu that includes icons and labels. I attempted to do this using Chips: {categories.map((category) => ( <Chip key={category._id} ...

Retrieve the key{index} property from the .map method in React for the element that was just clicked

I am facing an issue with my code const Component = () => { const [Clicked, setClicked] = useState(false); const handleClick = (prop, e) => { console.log(prop); } return ( <div> {arrayCard.map((item, i) => { ...

In the world of node.js, functions almost always have a tendency to

As a beginner in the world of nodejs, I am diving into various guides and screencasts to grasp the basics. One aspect that has caught my attention is the handling of async/sync operations, reading files, and understanding how nodejs deals with callbacks/re ...

Encountered a problem while trying to install my package from the npm registry - Error number 4058. The main.js file cannot be found in the

After creating a sample package and publishing it on the npm registry under my personal npm account with the name newtestmay, I encountered an error when trying to install it using the command npm install newtestmay. The error message below is extracted fr ...

Unveiling the Secret: Removing Duplicate Elements from an Array

I'm attempting to create a JavaScript function that can remove duplicates from an array without using the Set, filter, or reduce functions. I've tried using nested loops to compare elements and splice duplicates out of the array, but I seem to be ...

Tips for eliminating stuttering when fixing the position of an element with JavaScript

I am currently facing an issue with a webpage I created where the text freezes when scrolled down to the last paragraph, while the images continue to scroll. Although my implementation is functional, there is noticeable jankiness when using the mouse wheel ...

What could be causing my image not to show up on ReactJS?

I'm new to ReactJS and I am trying to display a simple image on my practice web app, but it's not showing up. I thought my code was correct, but apparently not. Below is the content of my index.html file: <!DOCTYPE html> <html> & ...

Determine the React component's position in relation to the viewport while scrolling, ideally in percentage

I'm searching for effective solutions to solve this issue that has me stumped, and haven't come across any suitable libraries. What I'm looking for specifically is a way to track a Component's vertical position (Y) when scrolling, but ...

What is the best way to use the event target as the argument for $emit in VueJS2?

I am working with a VueJS 2 template var aThing = Vue.component('something',{ template :` <button @click="$emit('custom-event','hello there')">Click me</button>`}); Can the actual button that was clicked ...

Methods for encoding and decoding special characters using either JavaScript or jQuery

I am looking for a solution to encode and decode various special characters using JavaScript or jQuery... ~!@#$%^&*()_+|}{:"?><,./';[]\=-` I attempted to encode them using the following code snippet... var cT = encodeURI(oM); // ...

Enhance your cloud functions by updating data

Recently, I encountered an issue with a function I wrote that interacts with the Real Time Database. Every time I attempted to write data to a specific node, it would add the complete dataset and then promptly delete everything except one entry. https://i ...

explore the route with the help of jquery scrolling feature

Is there a way to implement scrolling functionality for tab headers similar to this demo? I have a list of elements within a div that I need to scroll like the tabs in the demo. I attempted to achieve this by setting the position of the inner elements to ...