Looping through assets in Vue.js static directory

前端 未结 2 636
抹茶落季
抹茶落季 2020-12-18 08:41

I\'ve created a simple app in Vue (using the Webpack template) that has a carousel in it. What I would like to do is loop through all of the images in static/images

相关标签:
2条回答
  • 2020-12-18 08:55

    From this webpack documentation you can get all files in the directory or specific files based on a regex search pattern.

    You could do something like:

    var cache = {};
    
    function importAll (r) {
      r.keys().forEach(key => cache[key] = r(key));
    }
    
    importAll(require.context('../components/', true, /\.js$/));
    

    If you a need an array of image names from the server you could do this:

    <template lang="html">
       <div style="height: 100px">
         <div :key="key" v-for="(img, key) in images" >
           <img :src="imageDir + key.substr(1)" class="" >
         </div>
        </div>
     </template>
    <script>
    export default {
      data() {
        return {
          imageDir: "/your/path/to/images/", // you know this already just from directory structure
          images: {}
        }
      },
    
      mounted() {
        this.importAll(require.context(this.imageDir, true, /\.png$/))
      },
      methods: {
        importAll(r) {
          var imgs = {}
          r.keys().forEach(key => (imgs[key] = r(key)))
          this.images = imgs
        }
      }
    }
    </script>
    

    I am not entirely sure if I am doing it correctly but it return the images from the directory and displays them as expected.

    0 讨论(0)
  • 2020-12-18 09:00

    JavaScript can't directly access the contents of a file system. You'll have to pass the contents using a server-side script (PHP,NodeJs…). However, if you would go thought this you need that images named are sequential, then you can loop through names and check if image exist or not.

    I think it would be better if you have a service-side when your client can upload images, create an API to list all images, then you performer a get request.

    0 讨论(0)
提交回复
热议问题