Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through assets in Vue.js static directory

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 to create that carousel. I know this is probably a dumb question, but how would I go about doing this? Do I need to perform a GET request?

The reason I'm asking is because I'm going to hand this off to a client to be hosted on their server. They would like to be able to add additional images to the carousel themselves if needed.

Any help would be appreciated.

like image 280
user2909019 Avatar asked Jan 13 '18 02:01

user2909019


1 Answers

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.

like image 122
Devin Norgarb Avatar answered Nov 15 '22 08:11

Devin Norgarb