So I have very predictably named images, and would like to import all of them into Vue automatically for display on a web page. While using the Vue CLI, the only way I can get the program to see any images in my assets folder is if I hard code the image names; generating image names dynamically, as by string concatenation and using v-for, does not work. In my code template you'll see 7 "Face" components, 5 of which are commented and do not work. Only the 2 un-commented, hard-coded image definitions work, even though they all seem equivalent! Any idea how I can fix this issue?
<template>
<div id="app">
<Face :src="src" />
<div v-for="image in images" :key="image.id">
<!-- <Face :src="image.src"/> -->
<!-- <Face :src="getImage(image.src)"/> -->
<!-- <Face :src="require(image.src)"/> -->
<!-- <Face :src="`require('./assets/test${image.id}.png')`"/> -->
<Face :src="require('./assets/test0.png')"/>
</div>
<!-- <Face v-for="image in images" :key="image.id" :src="require(image.src)"/> -->
</div>
</template>
<script>
const _ = require('lodash');
import Face from './components/Face.vue'
const imageDir = "./assets/";
const images = [];
// Generate image names
for (let i of _.range(3)) {
let imageName = `${imageDir}test${i}.png`;
images.push({id: i, src: imageName});
console.log(images);
}
export default {
name: 'app',
data() {
return {
src: require("./assets/test0.png"),
images: images,
}
},
methods: {
getImage(url) {
return require(url);
},
},
components: {
Face
}
}
</script>
And for those asking for the Face component code (it's designed to be as simple as possible for now, since I'm just getting started with all this):
<template>
<div class="centered">
<img :src="src">
</div>
</template>
<script>
export default {
props: {
src: {
type: String,
required: true,
},
},
data() {
return {
}
},
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.centered {
margin: 0 auto;
}
</style>