Swapping the image source using a Vue dropdown menu

Recently I started using Vue and decided to implement a dropdown menu component (). The component pulls its list items from a JSON array structured as follows:

<template>
    <div id="app">
    <div id='container'>
        <ejs-dropdownlist id='dropdownlist' placeholder='Pick a name' :dataSource='images' :fields='fields'></ejs-dropdownlist>
    </div>
    <img v-for="image in images" :key="image.url" :src="require('@/assets/pics/' + image.url)">
  </div>
</template>

<script>
    export default {
        data() {
            return {
                images: [
                    {
                        id: 'm1',
                        name: 'Sample Name',
                        url: "../assets/pics/samplename.png"
                    },...

                    ],
                    fields : {text:'name', value:'id'}
            }
        }
    }
</script>

The current functionality displays all the images at once through the v-for loop. However, I want to extract the id/url from the selected name in the dropdown menu and pass it to the <img> tag so that only the corresponding image is displayed below. How can I achieve this? Thank you!

Answer №1

To properly display the selected image in your dropdown, you need to add a v-model="selected" binding:

<ejs-dropdownlist v-model="selected"></ejs-dropdownlist> 
data() {
  return {
    selected: null, // Keeps track of selected image
    images: [...]
  }
}

Do not use a v-for loop in your template as it will iterate through all images unnecessarily. Instead, use the selected image for the correct source:

<img v-if="selected" :src="require('@/assets/pics/' + selected.url)">

Ensure that your image objects only contain the image name, as the path to the assets folder is already set in the src binding:

{
   ...
   url: "samplename.png"
}

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

Utilize AngularJS to enable the forward and back buttons to fetch JSON data, but ensure that the data is only retrieved if the item meets

I have successfully implemented forward and back buttons for paging through data items in an array from a JSON file: Controller: dishControllers.controller('DrinkcardsController', ['$scope','$http','$routeParams', ...

Error in Node.js child_process: unable to access the property '_writableState' as it is undefined

I'm currently working on integrating ffmpeg's functionality into a Node.js API by utilizing the child_process library. However, I encounter an error when trying to pass data to ffmpeg's stdin pipe, specifically getting a TypeError: Cannot re ...

What causes a component to not update when it is connected to an Array using v-model?

Array1 https://i.stack.imgur.com/cY0XR.jpg Array are both connected to the same Array variable using v-model. However, when changes are made to Array1, Array2 does not update. Why is this happening? Process: Upon examining the logs, it can be observed th ...

Leveraging Nuxt.js with Axios on Google Firebase hosting

When I deploy my project to Firebase hosting, I encounter an issue with the axios baseURL and/or proxy settings defaulting to local values instead of the ones specified in the nuxt.config.js. This results in 404 errors. Although hardcoding my URLs resolve ...

Are your Promises.all functions executing at the incorrect timing?

I can't seem to understand why Promise.all is not working as expected. Even though the log shows that data for "Streak" and "Last Activity" is successfully retrieved towards the end, I want Promise.all to fetch the data only when everything is filled ...

Implementing Jquery to Identify the Matching Indices of Two Arrays

I need to find the indices of similar values in array1 and array2, and then save them in a variable named stored_index. array1 = ["50","51","52","53","54","55","56","57","58","59"]; array2 = ["59","55","51"]; The desired result for stored_index is: sto ...

Is it possible to utilize JSX independently of React for embedding HTML within a script?

Is it possible to incorporate inline HTML within a script using a library such as jsx? <script src="jsx-transform.js"></script> <script type="text/jsx"> define('component', function () { return (<div>test html code< ...

What is the best way to confirm if a Json response is empty or not?

{"PatientPastMedicalHistoryGetResult":{"PastMedicalHistory":[]}} The PastMedicalHistory object does not contain any values. How can I verify if it is empty? ...

Using an image instead of a checkbox when it is selected (Angular 4/Ionic 3)

Is there a way to swap out the checkbox for an image? I want this image to change dynamically based on whether the checkbox is checked or not. Unfortunately, adding a class doesn't seem to do the trick as it modifies all icons in the same column. The ...

The function in the method (in quasar) is not activated by the @change event

When I select an option, I am trying to retrieve the selected value in a function called within my methods. However, the function does not seem to be triggering. This is my code: From the template : <q-select filled v-model="invoice_product.tarri ...

how to use jQuery to hide a flash-containing div without losing its content

Hello, I created a modal with jQuery UI that is displaying in front of a flash movie. However, the HTML content inside the modal appears corrupted. I attempted to hide the movie just before the modal is triggered and make it reappear after closing the mo ...

Searching for values within an array using the ".includes" method

I'm curious if there's a method to determine if a string contains any characters that are also present in an array? const array = ["cake", "hello", "ok"]; const string = "hello"; let result = string.include ...

The issue of the keyboard disappearing on Chrome for Android while switching between different input

Issue with Input Switching on Chrome for Android I am facing difficulty when trying to switch between two input fields. The HTML code is as follows: <input type="text"/> <input type="text"/> When I enter text in the first input and click on ...

Find out the keycode of an event in ReactJS when a key is released

Whenever I try to get keyCode on a keyUp event, it always returns 0. Why is this happening? I want to avoid using keypress and similar methods, and I also need to utilize an arrow function: handleKeyPress = (e, type) => { let KeyCode = e.charCode; ...

updating dropdown options based on user input with PHP

I need help with implementing a code for two dropdown boxes. The first dropdown should display main category values dynamically, and when a value is selected, the second dropdown should appear with corresponding sub-category values. How can I achieve this ...

What are the steps to integrating JavaScript autocomplete into a website?

I am relatively new to the world of programming, particularly when it comes to JavaScript/jQuery. I have been searching online for a solution to enable autocomplete in my search feature, but despite trying various approaches found on the internet, I have y ...

How can we apply position: fixed in print media queries using CSS?

In order to display a footer on every printed page, we have implemented the use of position: fixed. However, one issue that has arisen is that content ends up flowing underneath the footer. Is there a solution to prevent this from happening while still k ...

Difficulty with rendering a React component in a basic demonstration

I'm trying to display "Hi", but even though I'm not getting any errors, nothing is showing up on the screen. Can anyone assist with this issue? <html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15. ...

Looping through the ajax data to populate ion-item elements

I am currently working on a loop that retrieves user IDs, names, etc. from a JSON file. I am trying to display this data in a list view within an Ionic framework. When I simply use direct alerts in JavaScript, the users are displayed correctly, but when I ...

What is the best way to use a button to hide specific divs upon clicking?

Is there a way to use a button onclick event to hide specific divs within a parent div? I've tried using .toggleClass('.AddCSSClassHere') but I'm not sure how to apply it to multiple divs. The jQuery snippet provided only allows me to h ...