首页 > 解决方案 > src 属性中的 VueJS 插值

问题描述

在带有 TypeScript 和 Vuetify 应用程序的 VueJS 中,我有十张图片,分别称为 picture1.png、picture2.png、picture3.png 等。我正在尝试<div><img src="../assets/pictures/picture1.png"/></div>为每张图片制作。这是我的代码:

<template>
    <div class="home">
        <div class="pictures">
            <div v-for="index in Array.from({length: 10}, (v, k) => k+1)" :key="index">
                <img src='../assets/pictures/picture{{index}}.png'>
            </div>
        </div>
    </div>
</template>

这有一个错误,即属性中的插值已被删除。正如回答这个问题所解释的那样,您应该使用 v-bind 代替:

<template>
<div class="home">
    <div class="picture">
        <div v-for="index in Array.from({length: 10}, (v, k) => k+1)" :key="index">
            {{index}}
            <img :src="'../assets/pictures/picture' + index + '.png'">
        </div>
    </div>
</div>

例如,输出十张损坏的图像, src 字面意思是这样的: src="../assets/pictures/picture1.png"

并且该文件不存在,因此它显示损坏的图像图标。

如果我只使用<img src='../assets/pictures/picture1.png'>,它可以工作,并且 dom 检查器中显示的图像 url 是<img src="/img/picture1.ea361a2e.png">.

有没有办法src在 Vue 中动态地正确处理构建 img s,但仍然允许它以处理普通srcs 的方式处理它而无需动态绑定?

标签: typescriptvue.jssrcvuetify.js

解决方案


我很幸运地做了以下事情。

:src="require(`images/image-${index}.png`)"

推荐阅读