Vue.js - Using v-for to dynamically create images not working; src not found












-1














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>












share|improve this question
























  • please provide the relevant code of Face
    – Boussadjra Brahim
    Nov 12 at 1:34










  • @BoussadjraBrahim if the one works, Face is not needed
    – Derek Pollard
    Nov 12 at 1:36










  • i think the images array is empty
    – Boussadjra Brahim
    Nov 12 at 1:46










  • No, it isn't. When using the images array, I get the following type of error: [Vue warn]: Error in render: "Error: Cannot find module './assets/test0.png'" The v-for directive on the div works fine with the image array, so the code that I have above shows 4 of the same image.
    – user3225632
    Nov 12 at 1:49










  • @user3225632 have you tried <Face :src="require('./assets/test' + image.id + '.png')"/>
    – Derek Pollard
    Nov 12 at 1:55


















-1














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>












share|improve this question
























  • please provide the relevant code of Face
    – Boussadjra Brahim
    Nov 12 at 1:34










  • @BoussadjraBrahim if the one works, Face is not needed
    – Derek Pollard
    Nov 12 at 1:36










  • i think the images array is empty
    – Boussadjra Brahim
    Nov 12 at 1:46










  • No, it isn't. When using the images array, I get the following type of error: [Vue warn]: Error in render: "Error: Cannot find module './assets/test0.png'" The v-for directive on the div works fine with the image array, so the code that I have above shows 4 of the same image.
    – user3225632
    Nov 12 at 1:49










  • @user3225632 have you tried <Face :src="require('./assets/test' + image.id + '.png')"/>
    – Derek Pollard
    Nov 12 at 1:55
















-1












-1








-1







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>












share|improve this question















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>








<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>





<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>





<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>





<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>






javascript vue.js






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 12 at 1:39

























asked Nov 12 at 1:27









user3225632

11




11












  • please provide the relevant code of Face
    – Boussadjra Brahim
    Nov 12 at 1:34










  • @BoussadjraBrahim if the one works, Face is not needed
    – Derek Pollard
    Nov 12 at 1:36










  • i think the images array is empty
    – Boussadjra Brahim
    Nov 12 at 1:46










  • No, it isn't. When using the images array, I get the following type of error: [Vue warn]: Error in render: "Error: Cannot find module './assets/test0.png'" The v-for directive on the div works fine with the image array, so the code that I have above shows 4 of the same image.
    – user3225632
    Nov 12 at 1:49










  • @user3225632 have you tried <Face :src="require('./assets/test' + image.id + '.png')"/>
    – Derek Pollard
    Nov 12 at 1:55




















  • please provide the relevant code of Face
    – Boussadjra Brahim
    Nov 12 at 1:34










  • @BoussadjraBrahim if the one works, Face is not needed
    – Derek Pollard
    Nov 12 at 1:36










  • i think the images array is empty
    – Boussadjra Brahim
    Nov 12 at 1:46










  • No, it isn't. When using the images array, I get the following type of error: [Vue warn]: Error in render: "Error: Cannot find module './assets/test0.png'" The v-for directive on the div works fine with the image array, so the code that I have above shows 4 of the same image.
    – user3225632
    Nov 12 at 1:49










  • @user3225632 have you tried <Face :src="require('./assets/test' + image.id + '.png')"/>
    – Derek Pollard
    Nov 12 at 1:55


















please provide the relevant code of Face
– Boussadjra Brahim
Nov 12 at 1:34




please provide the relevant code of Face
– Boussadjra Brahim
Nov 12 at 1:34












@BoussadjraBrahim if the one works, Face is not needed
– Derek Pollard
Nov 12 at 1:36




@BoussadjraBrahim if the one works, Face is not needed
– Derek Pollard
Nov 12 at 1:36












i think the images array is empty
– Boussadjra Brahim
Nov 12 at 1:46




i think the images array is empty
– Boussadjra Brahim
Nov 12 at 1:46












No, it isn't. When using the images array, I get the following type of error: [Vue warn]: Error in render: "Error: Cannot find module './assets/test0.png'" The v-for directive on the div works fine with the image array, so the code that I have above shows 4 of the same image.
– user3225632
Nov 12 at 1:49




No, it isn't. When using the images array, I get the following type of error: [Vue warn]: Error in render: "Error: Cannot find module './assets/test0.png'" The v-for directive on the div works fine with the image array, so the code that I have above shows 4 of the same image.
– user3225632
Nov 12 at 1:49












@user3225632 have you tried <Face :src="require('./assets/test' + image.id + '.png')"/>
– Derek Pollard
Nov 12 at 1:55






@user3225632 have you tried <Face :src="require('./assets/test' + image.id + '.png')"/>
– Derek Pollard
Nov 12 at 1:55














1 Answer
1






active

oldest

votes


















0














I was able to circumvent the problem somewhat by importing all the images in my directory, using code adapted from
here, shown below:






function importAll(r) {
let images = {};
r.keys().map((item, index) => { images[item.replace('./', '')] = r(item); });
return images;
}

const images = importAll(require.context('./assets/', false, /.(jpg)$/));





However, I found it odd that the importAll statement completely breaks down if you replace ‘./assets/’ with a variable, as in the following case:






const imageDir = './assets/'
const images = importAll(require.context(imageDir, false, /.(jpg)$/));





This odd behavior is apparently just something you have to work around when dealing with Webpack.






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53254933%2fvue-js-using-v-for-to-dynamically-create-images-not-working-src-not-found%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    I was able to circumvent the problem somewhat by importing all the images in my directory, using code adapted from
    here, shown below:






    function importAll(r) {
    let images = {};
    r.keys().map((item, index) => { images[item.replace('./', '')] = r(item); });
    return images;
    }

    const images = importAll(require.context('./assets/', false, /.(jpg)$/));





    However, I found it odd that the importAll statement completely breaks down if you replace ‘./assets/’ with a variable, as in the following case:






    const imageDir = './assets/'
    const images = importAll(require.context(imageDir, false, /.(jpg)$/));





    This odd behavior is apparently just something you have to work around when dealing with Webpack.






    share|improve this answer




























      0














      I was able to circumvent the problem somewhat by importing all the images in my directory, using code adapted from
      here, shown below:






      function importAll(r) {
      let images = {};
      r.keys().map((item, index) => { images[item.replace('./', '')] = r(item); });
      return images;
      }

      const images = importAll(require.context('./assets/', false, /.(jpg)$/));





      However, I found it odd that the importAll statement completely breaks down if you replace ‘./assets/’ with a variable, as in the following case:






      const imageDir = './assets/'
      const images = importAll(require.context(imageDir, false, /.(jpg)$/));





      This odd behavior is apparently just something you have to work around when dealing with Webpack.






      share|improve this answer


























        0












        0








        0






        I was able to circumvent the problem somewhat by importing all the images in my directory, using code adapted from
        here, shown below:






        function importAll(r) {
        let images = {};
        r.keys().map((item, index) => { images[item.replace('./', '')] = r(item); });
        return images;
        }

        const images = importAll(require.context('./assets/', false, /.(jpg)$/));





        However, I found it odd that the importAll statement completely breaks down if you replace ‘./assets/’ with a variable, as in the following case:






        const imageDir = './assets/'
        const images = importAll(require.context(imageDir, false, /.(jpg)$/));





        This odd behavior is apparently just something you have to work around when dealing with Webpack.






        share|improve this answer














        I was able to circumvent the problem somewhat by importing all the images in my directory, using code adapted from
        here, shown below:






        function importAll(r) {
        let images = {};
        r.keys().map((item, index) => { images[item.replace('./', '')] = r(item); });
        return images;
        }

        const images = importAll(require.context('./assets/', false, /.(jpg)$/));





        However, I found it odd that the importAll statement completely breaks down if you replace ‘./assets/’ with a variable, as in the following case:






        const imageDir = './assets/'
        const images = importAll(require.context(imageDir, false, /.(jpg)$/));





        This odd behavior is apparently just something you have to work around when dealing with Webpack.






        function importAll(r) {
        let images = {};
        r.keys().map((item, index) => { images[item.replace('./', '')] = r(item); });
        return images;
        }

        const images = importAll(require.context('./assets/', false, /.(jpg)$/));





        function importAll(r) {
        let images = {};
        r.keys().map((item, index) => { images[item.replace('./', '')] = r(item); });
        return images;
        }

        const images = importAll(require.context('./assets/', false, /.(jpg)$/));





        const imageDir = './assets/'
        const images = importAll(require.context(imageDir, false, /.(jpg)$/));





        const imageDir = './assets/'
        const images = importAll(require.context(imageDir, false, /.(jpg)$/));






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 12 at 4:06

























        answered Nov 12 at 3:48









        user3225632

        11




        11






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53254933%2fvue-js-using-v-for-to-dynamically-create-images-not-working-src-not-found%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            這個網誌中的熱門文章

            Academy of Television Arts & Sciences

            L'Équipe

            1995 France bombings