Leveraging the source of an image from asset variables

Lately, I've been experiencing issues with displaying images on my page, specifically when trying to show a list of images.

The problem arises when attempting to store the image URL in a variable or object instead of hardcoding it directly into the src attribute. When I try to reference the URL using :src="myVariable", which contains the URL, it doesn't work as expected.

For example:

<template>
  <div>
    Problem with images
    <img :src="image.url" alt="">
    <img :src='require(image.url)' alt="">
  </div>
</template>

<script>
export default {
  data () {
    return {
      image:
        {
          url: '~/assets/icon.png',
          type: 'asset'
        }
    }
  }

}
</script>

In this scenario, I have experimented with different variations of referencing assets using ~ and @, but encountered errors due to the way the image URL is provided via a variable rather than directly.

I attempted to address this issue by creating an object that includes the image URL and its type (asset/static) and then checking if the type is asset before using require(variable). However, I ran into an error stating:

"Cannot find module '~/assets/icon.png'"

Has anyone found a solution to this problem?

Answer №1

When dealing with binding to an asset variable image, make sure to use the require method. Here's an example:

<img :src="url">
url: require('@/assets/icon.png')

If your JSON file only includes the filename, you can incorporate the require method in the template like this:

<img :src="require('@/assets/' + url)">
url: 'icon.png'

Answer №2

Shoutout to Dan for sharing his brilliant solution with me. I finally have a universal solution for handling images, including their links and types:

image: {
  url: '/any-asset-folder/image.png'
  type: 'asset'
}

Using a ternary operator, the result is:

<img
  :src="image.type === 'asset' 
    ? require('@/assets'+image.url) 
    : image.url"
>

Now, I can seamlessly display images whether they come from assets, static files, or external sources.

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

unable to perform a specific binary operation

Is there an efficient method to achieve the following using binary operations? First byte : 1001 1110 Second byte : 0001 0011 Desired outcome : 1000 1100 I am looking to reset all bits in the first byte that correspond to bit values of 1 in the secon ...

Update the getJSON filter to only include specific results and exclude the majority

In an effort to streamline my chart to only include data for "zelcash", I am currently faced with the issue of fluctuating values causing the line graph to be inconsistent. This is because the results show zelcash with 0 as the hashrate, along with actual ...

After submitting the axios method, the page will automatically redirect upon a successful result

In my Laravel app, I am using Axios to submit a form with the following script: <script> export default { props: [ 'route' ], data: function () { return { mobile: '' } }, methods: { submitMobile(){ ...

AngularJS is a highly intuitive platform that incorporates Google Maps for

I am relatively new to using Angular and decided to experiment with integrating Google Maps into my project. Here's what I need: I have a search bar for finding restaurants. The API returns the address, latitude, and longitude of the restaurant searc ...

Launching a URL in a pop-up window with customized title and address bar

I am seeking to implement a feature similar to the following: <a href="post/23">post 23</a> When a user clicks on this element, I want a popup div to fade in and load the HTML from page post/23 into it. Additionally, I would like the title an ...

What is the best way to retrieve the value of the "Observer" object?

I am a user of Vue.js and I have the following data in this.suspendedReserveMemo: this.suspendedReserveMemo [__ob__: Observer]650: "memo3"651: "memo4"652: ""653: ""654: ""655: ""656: ""657: ""658: ""659: ""660:""661: ""662: ""length: 663__ob__: Observer {v ...

How are the actions in react redux able to utilize dispatch and getState methods?

Could you please explain how the actions.js in the reddit example of the react redux docs is able to access the dispatch and getState functions without importing them explicitly? I was under the assumption that every method needed to be imported in each ...

Enhance your bookmarking experience with Vue mixins that allow you to easily customize the color

Looking for a way to efficiently bookmark pages in my application, I have successfully implemented a feature where I can add pages by their name and URL into bookmarks. Upon clicking the bookmark button, it changes color to indicate that the page has been ...

Is there a way for me to extract and showcase the initial 10 items bearing a particular class name from a different html document on my homepage?

I am looking to extract a list of movies from an HTML file titled "movies.html". The structure of the file is as follows: <div class="movie">Content 1</div> <div class="movie">Content 2</div> <div class=" ...

IE may not support the use of XMLHttpRequest with the POST method

When interacting with a server through an XMLHttpRequest to post data, the code typically follows this structure: var xhr = new XMLHttpRequest(); var url = 'http://myurl/post'; xhr.open("POST", url, true); xhr.setRequestHeader("Content-type", " ...

Ways to verify the input fields across multiple tabs

Utilizing jquery validate along with jquery tabs to construct a multi-tab form. Consider a basic form : tab 1 for entering address, tab 2 for entering name, tab 3 for submission HTML <ul class="nav nav-tabs"> <li class="active"><a hr ...

How can I update an Angular Datatable to display new JSON data?

I have a Datatable controller set up as shown below: //Module / Módulo var angularDataTables = angular.module("angularDataTables", ['datatables', 'datatables.buttons' , 'datatables.bootstrap']); //Controller / Controlador ...

Extract portions of the date into individual variables

My current project involves creating a front-end interface for data stored in a JSON database. The date information is saved in the following format: 12/31/16 I am trying to extract each of these values individually. Is there a method to assign variabl ...

Creating a copy of a div using jQuery's Clone method

I need help figuring out how to clone a div without copying its value. I've attempted various methods, but they all seem to include the value in the cloned element. This is the jQuery function I am currently using: $('#add_more').click(fu ...

Enhance a React component by including additional properties when passing it into another component through props

I have a parent element with a dynamically changing height that I need to pass down to its child elements. To get and set the height of the parent element, I am utilizing a ref. The challenge lies in passing this height value from the parent component to ...

Photo uploading in ASP.NET MVC - encountering null HttpPostedFileBase issue

QUESTION: I'm having an issue where the Photo1 value is null in the controller post method despite uploading it. Can someone help with this? This is my model class: class ProductVM{ public string Name { get; set;} public string Color {get; ...

Finding elements based on their position using Javascript

I'm searching for an optimal method to identify all elements located within a specific range of pixels from the top of the page. Currently, I have implemented a straightforward test called inRange function inRange(el, from, to) { var top = el.offs ...

Struggling to decide on the perfect CSS selector for my puppeteer script

I am trying to use puppeteer page.type with a CSS selector. <div class="preloader"> <div class="cssload-speeding-wheel"></div> </div> <section id="wrapper" class="login-register"> <div class="login-box"> <d ...

Eliminate every instance using the global regular expression and the replace method from the String prototype

function filterWords(match, before, after) { return before && after ? ' ' : '' } var regex = /(^|\s)(?:y|x)(\s|$)/g var sentence1 = ('x 1 y 2 x 3 y').replace(regex, filterWords) console.log(sentence1) sentence2 ...

Having trouble with looping through subarrays using Javascript and JSON

I am attempting to iterate through a JSON object using Javascript (jQuery). Within the main JSON object, each object in the array contains embedded arrays of tags. My goal is to loop through all the files in the main object and simultaneously iterate thro ...