Search code examples
imagevue.jssrcv-for

Vue.js generate img tag with v-for and auto src binding


I am really stuck to render <img> objects with the v-for directive.

First of all, I would try to get a url list in a directory with 'require context'. (It's successful)

Then I tried to iterate that url list with v-for and to bind to <img src>.

But it's not working and I tried many different kinds of ways but it wasn't helpful.

So any guys who can solve this problem? or just give me hints. Thanks for reading.

<template>
    <div>
        <h2>Paintings</h2>
        <section>
            <!-- This is one of right url path that I want to implement -->
            <img src="../../artproject/temp/./1.jpg"> 

            <!-- This is the problem part -->
            <li v-for="url in getURL()" v-bind:key="url">
                <img :src=base+url>
                <!-- <img onload="this.setAttribute('src', url)" > -->
            </li>
        </section>
    </div>
</template>
<script>
    export default {
        data() {
            return {
                base: "../../artproject/temp/",
            }
        },
        methods: {
            getURL() {
                const paintings = require.context(
                    '../../artproject/temp',
                    true,
                    /.*\.jpg$/
                )
                return paintings.keys()
            },
        }
    }
</script>

Rendered result is bit not understandable.. V-for rendering's src url seems like right. but with the given url is change on first image.


Solution

  • Dynamic image source does not work with Vue.js. The reason is that the code goes into a bundler (webpack for example) and generates your bundle and your assets in function of what you wrote. If you want to have a dynamic image source in a v-for, you have to require all the images.