0

I am trying to generate src link to each of my li items generated by v-for.

I have list of some Strings... ["Electronics","Furniture", "Cloths", "Sports", "Entertainment", "Others"] and in each tag

  • I want to generate some with dynamically changing src.

    For example:
    First item is electronics so path would be @/assets/Electronics.png and image would be displayed Second item is Furniture so path would be @/assets/Furniture.png

    What do I need to do to show that img how do I need to define this path?

    <ul class="menu-dropdown"> <li v-for="item in items" :key="item" class="center align-self-center"> <img class="float-left" :src="getPicture(item)" v-bind:alt="item" /> <a href="#"><h3>{{item}}</h3></a> </li> </ul> <script> export default { name: 'Header', props:{}, data() { return { items: ["Electronics", "Furniture", "Cloths", "Sports", "Entertainment", "Others"] } }, methods:{ getPicture(item){ return '@/assets/' + item + ".png" } } } </script> 
  • 2
    • 1
      You need to use require. Something like return require('@/assets/' + item + '.png'). Commented Sep 20, 2020 at 23:06
    • Also, don't use methods to render parts of your template. Try :src="require(`@/assets/${item}.png`)" Commented Sep 20, 2020 at 23:53

    1 Answer 1

    1

    In the data property

    I think you should make array of object with name and src, then import every images.

    <script> import electronicSrc from "@/path/to/img/electronic"; import furnitureSrc from "@/path/to/img/furniture"; export default { name: 'Header', props:{}, data() { return { items = [{ category: "Electronics", src: electronicImg}, { category: "Furniture", src: furnitureImg}, { category: "Cloths", src: clothImg}, .. ]; } }, } </script> 

    Modify the template

    <li v-for="item in items" :key="item" class="center align-self-center"> <img class="float-left" :src="item.src" v-bind:alt="item.category" /> <a href="#"><h3>{{ item.category }}</h3></a> 
    Sign up to request clarification or add additional context in comments.

    2 Comments

    👍 Also might be nice to make an index.js file that exports all the image modules
    Yeah, @Phil right, thanks!

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.