如何在Vue中将img src绑定到数据 [英] How to bind img src to data in Vue
问题描述
我的 vue webpack 脚本中有以下内容:
然后在我的 html 中,我试图将本地 src 元素绑定到一个 img 但我无法让它工作.这是我的 html 的样子:
<img :src="repo.src"/>
当我的 img 源不是像这样的数据绑定时它工作正常:
如果我的本地图片在 Vue 中是数据绑定的,为什么它们不会加载?
这是我的目录的样子:
如果您使用 vue-cli
,您必须记住,所有内容都作为模块处理,包括图像.如果路径在 JS 中是相对的,则需要使用 require
,如下所示:
{ name: 'test1', src: require('../assets/logo.png') }
你可以在这里找到更多细节:http://vuejs-templates.github.io/webpack/static.html
I have in my vue webpack script the following:
<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:
<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 :src="../assets/logo.png" />
Why won't my local images load if they are data bound in Vue?
Here is what my directory looks like:
If you're using vue-cli
you have to remember that everything is processed as a module, even images. You'd need to use require
if the path is relative in JS, like this:
{ 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
这篇关于如何在Vue中将img src绑定到数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!