Vue.js 使用 v-for 和自动 src 绑定生成 img 标签
Vue.js generate img tag with v-for and auto src binding
我真的坚持使用 v-for
指令渲染 <img>
对象。
首先,我会尝试在 'require context' 的目录中获取 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>
动态图像源不适用于 Vue.js。原因是代码进入捆绑器(例如 webpack)并根据您编写的内容生成捆绑包和资产。如果你想在 v-for 中有一个动态图像源,你必须要求所有图像。
我真的坚持使用 v-for
指令渲染 <img>
对象。
首先,我会尝试在 'require context' 的目录中获取 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>
动态图像源不适用于 Vue.js。原因是代码进入捆绑器(例如 webpack)并根据您编写的内容生成捆绑包和资产。如果你想在 v-for 中有一个动态图像源,你必须要求所有图像。