javascript 如何在Vue中将img src绑定到数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48847644/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to bind img src to data in Vue
提问by rockzombie2
I have in my vue webpack script the following:
我的 vue webpack 脚本中有以下内容:
<script>
export default {
data () {
return {
repos: [
{name: 'test1', src: '../assets/logo.png'},
{name: 'test2', src: '../assets/underscore.png'},
...
]
}
}
}
</script>
And then in my html, I'm trying to bind the local src element to an img but I can't get it to work. Here is what my html looks like:
然后在我的 html 中,我试图将本地 src 元素绑定到一个 img 但我无法让它工作。这是我的 html 的样子:
<div v-for="repo in repos" :key="repo.name">
<img :src="repo.src" />
</div>
It works fine when my img source is not data-bound such as this:
当我的 img 源不是数据绑定时,它工作正常,例如:
<img :src="../assets/logo.png" />
Why won't my local images load if they are data bound in Vue?
如果在 Vue 中绑定了数据,为什么我的本地图像不会加载?
Here is what my directory looks like:
这是我的目录的样子:
回答by Bill Criswell
If you're using vue-cliyou have to remember that everything is processed as a module, even images. You'd need to use requireif the path is relative in JS, like this:
如果您正在使用,vue-cli您必须记住一切都作为一个模块进行处理,即使是图像。require如果路径在 JS 中是相对的,则需要使用,如下所示:
{ name: 'test1', src: require('../assets/logo.png') }
You can find a lot more details about this here: http://vuejs-templates.github.io/webpack/static.html
您可以在此处找到更多详细信息:http: //vuejs-templates.github.io/webpack/static.html
回答by sina
simply for binding img src to data, just require the file address:
只是为了将 img src 绑定到数据,只需要文件地址:
<img v-bind:src="require('../image-address/' + image data)" />
<img v-bind:src="require('../image-address/' + image data)" />
example below shows ../assets/logo.png :
下面的示例显示../assets/logo.png :
<template>
<img v-bind:src="require('../assets/' + img)" />
</template>
<script>
export default {
data: function() {
return {
img: "logo.png"
};
}
};
</script>


