Vue.js生成带有v-for和自动src绑定的img标签

时间:2019-12-28 16:42:25

标签: image vue.js src v-for

我真的很想用<img>指令渲染v-for对象。

首先,我将尝试在带有“需要上下文”的目录中获取一个URL列表。 (成功)

然后,我尝试使用v-for迭代该URL列表并绑定到<img src>

但是它不起作用,我尝试了许多不同的方法,但是没有帮助。

那么有谁能解决这个问题?或只是给我提示。感谢您的阅读。

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

1 个答案:

答案 0 :(得分:1)

动态图像源不适用于Vue.js。原因是代码进入了捆绑程序(例如webpack),并根据您编写的内容生成了捆绑包和资产。如果要在v-for中使用动态图像源,则必须要求所有图像。