Creating interactive image paths using Vue.js

Check out this relevant codepen

I'm currently working on a project that involves generating dynamic image paths, but it seems like I might be overlooking something crucial. For some reason, the method responsible for altering the src attribute in the img tags isn't functioning as expected.

Below is the HTML snippet in question:

<div id="app">

  <component v-bind:fruits="fruits" is="fruits-list"></component>

</div>

<template id="fruits-template">
  <div>
    <ul>
      <li v-for="fruit in fruits">
        {{ fruit }}
        <img src="imgName(fruit)" />
      </li>
    </ul>
  </div>
</template>

In addition, here is the relevant JavaScript code snippet:

Vue.component('fruits-list', {
  template:'#fruits-template',
  props: ['fruits'],
  methods: {
    imgName: function(fruit){
      var imgPath = 'assets/images/' + fruit + '.jpg';
      return imgPath;
    }
  }
})

new Vue({
  el: '#app',
  data() {
    return {
      fruits: ['apple','pear','strawberry', 'peach']
    }
  }
})

I did experiment with binding the src directly to the img tag like so:

<img :src="getImageUrl(fruit)" />

However, this resulted in nothing rendering at all. In situations like this, would it be more suitable to utilize methods or computed properties within an instance?

Answer №1

Give this html code a try:

<img v-bind:src=imgName(fruit) />

Upon testing this on your pen, an unsuccessful request to the specified URL is seen, along with similar issues for the other fruits:

Request URL:https://codepen.io/boomerang/iFrameKey-9b0f86ca-8c55-3b83-2d9c-3367ada2ac69/assets/images/apple.jpg

Do the images for these fruits exist in their expected locations? By altering the imgName function as shown below, the apple image successfully loads within the pen:

imgName: function(fruit){
  if (fruit === 'apple') {
    return 'https://bestapples.com/wp-content/uploads/2015/10/apple-varieties.jpg'
  } else {
    var imgPath = 'assets/images/' + fruit + '.jpg';
    return imgPath;        
  }

}

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

Display Image based on AngularJS value

Within my data, there exists a value {{catadata2.EndorsementList['0'].Rating}}. This value can be either 3, 4, or 5. Based on this value, I am looking to display the image <img src="/assets/img/rating.png" /> a certain number of times. For ...

When attempting to use the POST method with a JSON body in Postgresql, I encounter an error

Encountering an error: There seems to be an issue with a JSON token at position 197 while trying to parse it. It occurs in the following code snippet: at JSON.parse () at parse (C:\Users\hp\empServers\node_modules\body-parser&bso ...

executing a javascript function in PHP following form submission

Having trouble calling a javascript function after submitting a form and experiencing errors? New to PHP and seeking assistance. Any advice is appreciated. if(!empty($varAccountType)) { <?php if($varAccountType=='Free Account') { ...

Incorporating asynchronous file uploads to a server using a for loop

I am in the process of transforming my original code into "async" code. The initial code queries the database and retrieves the results, which includes images. I want to optimize writing the images asynchronously to my nodejs server as the current synchro ...

Is there a way to extract video frames from a WebRTC local stream and transfer them to Python?

I am in the process of developing a video call application similar to Google Meet or Zoom, incorporating object detection using Python Flask or Django. Here is how the application functions: Users can join a channel for the video call The camera ini ...

Get the first element of a 2-dimensional array after sorting it

In my possession is the following 2D array: [["fox", "100"], ["the", "1"], ["quick", "50"]] The task at hand is to keep only the first element of the array, but have it sorted based on the second ...

In a Vue serverless web application, OpenLayers Map object fails to trigger events

In my Vue serverless web application, I have implemented an OpenLayers map initialized in the mounted lifecycle method. The map is populated with ImageWMS layers that are updated by various functions. After updating the parameters of these layers, I call ...

Ways to increase the shrinking capacity of flex items when the entire container width is occupied

Recent Post Below: I've replicated a minimized issue: https://codepen.io/MH-123/pen/ExJWQWq?editors=1100 In the provided CodePen, the problem persists. Two divs are present, but flex shrink functionality is not working as expected. The main flex cont ...

Creating a Mongoose Schema for implementing the delete functionality

I'm having trouble deleting items from a MongoDB list. It seems that when the axios.delete method is called in the ExpensesListItem.tsx file, the item is not being deleted and no error message is displayed in the console. I suspect there might be an ...

Tips for tracking the number of selected checkboxes in Angular?

Utilizing $watch, I attempted to showcase the counter value. However, the counter value has not increased yet, To keep count, $scope.$watch('items', function(items){ var selectedItems = 0; angular.forEach(items, function(item){ selectedItems + ...

What is the best way to implement this component into my vue.js project?

I am having trouble integrating this vue component into my app as it is not loading properly. You can find the source of the component here. The following warnings are showing up: Unresolved function or method isNumeric() at line 35 Unused parameter e at ...

Vue's Post Request Triggering Data Changes

Encountering a challenge where the data does not update correctly when a new object is included in the array. The current process involves looping through an array of engagements associated with a client as shown below: <div class="row mx-2 px-2 justif ...

employing async/await in the function of a backend API

I'm facing an issue with the following code snippet: service.js module.exports = { getUser }; async function getUser({ data }) { return new Promise((resolve, reject) => { const id = data["id"]; const doc = await db.colle ...

A process of associating a single object with an array containing numerous objects

Can someone help me convert the following data structure? { role:'admin', resource:['calendar','appraisal'], action:['create:any','read:any','update:any','delete:any'] } { role:&apos ...

Converting a browser buffer to a string may not yield the same result in both a browser environment and

I've come across a puzzling problem while using node v8.1.4. Here's the buffer I'm dealing with: [ 191, 164, 235, 131, 30, 28, 164, 179, 101, 138, 94, 36,... ] When attempting to convert it to utf8 in both Node.js and the browser, I notic ...

Angular: Monitoring changes in forms

Currently, I am working on developing an Angular application where I need to monitor any changes in the form and execute specific operations based on those changes. While I am aware that this can be done using $scope.watch, I am concerned about the impact ...

JavaScript code using jQuery's ajax method is sending a request to a PHP server, but

Attempting to utilize jQuery ajax for PHP call and JSON return. The test is quite simple, but only receiving an empty object in response. No PHP errors appearing in the LOG File. jqXHR is recognized as an object with 'alert', yet not displayin ...

Retrieving the text content from a JSON key

I have the following JSON data saved in a jQuery variable called "jsondata": var jsondata = { "Name": { "Jaken": {}, "Test": {}, "Hello": {} }, "Date": { "Today": {}, "Tomorrow": {}, "Wednesday": {} }, "Description": { ...

Database storage of image tags on websites, similar to functionality found on social media platforms such as Facebook

Looking for an image tagging solution for websites that can save tag data directly to a database instead of a local file? I've checked out , but it doesn't support database integration in the current version. Ideally, I need a solution that is co ...

Retrieving the background image from the main page

Struggling to locate the background image on this website. Even after using Chrome dev tools and viewing the source, I can't seem to find it. It's like they are hiding the link to the background image very well. Any assistance in finding it would ...