Search code examples
javascriptvue.jsvuejs2vue-componentsyncfusion

Changing <img> src with a dropdown menu with Vue


I'm new to Vue and I'm using this dropdown menu component (https://ej2.syncfusion.com/vue/documentation/drop-down-list/data-binding/) that pulls it's list items from a json array that looks like this:

<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>

What this currently does is just list out all the images at once via the v-for loop, but I want to grab the id/url from the selected name in the dropdown menu and pass it to the <img> tag to have only the corresponding image be shown below, how would I go about doing this? Thanks!


Solution

  • Your dropdown needs a v-model="selected" binding to communicate the selected image to the parent:

    <ejs-dropdownlist v-model="selected"></ejs-dropdownlist> 
    
    data() {
      return {
        selected: null, // Used by the dropdown
        images: [...]
      }
    }
    

    A v-for would cause the template to loop through all images so you don't want that. Remove that and use the selected image for the correct src:

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

    Another issue will be that your image objects should have only the name of the image, as the assets path is hardcoded into the src binding:

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