Read contents of file into array inside vue component

Asked By: Anonymous

directory structure

Inside my media.txt file, I have:

"https://www.dropbox.com/s/******/687.jpg?dl=0",
"https://www.dropbox.com/s/******/0688.jpg?dl=0

I have the following Vue carousel component:

<template>
  <section>
    <v-card
        class="mx-auto"
        color="#26c6da"
        dark
        max-width="1200"
      >

      <v-carousel>
        <v-carousel-item v-for="(item,i) in items" :key="i" :src="item.src"></v-carousel-item>
      </v-carousel>

    </v-card>
  </section>
</template>

<script>
var cache = {};
// const images = require.context('../static/', false, /.png$|.jpg/);
// const images = require.context('../static/', false, /.png$|.jpg|.mp4/); // WORKING
const images = require.context('../static/media.txt', false, /.png$|.jpg|.mp4/);
var imagesArray = Array.from(images.keys());
// const images = ["./52lv.PNG", "./Capture1.PNG", "./maps.PNG"]
console.log(images.keys());
console.log('images');
console.log(images);
var constructed = [];
function constructItems(fileNames, constructed) {
  fileNames.forEach(fileName => {
    constructed.push({
      'src': fileName.substr(1)
    })
  });
  return constructed;
}
console.log('items ');
console.log(imagesArray);
// At build-time cache will be populated with all required modules. 
var res = constructItems(imagesArray, constructed);
console.log(res);
export default {
  data: function() {
    return {
      items: res
    };
  }
};
</script>

I want to read the images from the media.txt file into an array, then populate the carousel src with these. I’ve been trying with Webpack’s require.context function, but I’m getting a module not found error.

How can I get this working?


Solution

Answered By: Anonymous

It looks like you’re trying to import a string array (JSON) into a variable. That string array should be delimited by square brackets like this:

[
  "foo",
  "bar"
]

require.context(dirPath, useSubDirs, filenameRegex) is not the appropriate API to use here, as that method imports multiple files from a specified directory. For instance, the code below tells Webpack to load *.png, *.jpg, and *.mp4 files from the directory named ../static/media.txt (which presumably is actually a file).

require.context('../static/media.txt', false, /.png$|.jpg|.mp4/) // DON'T DO THIS

Instead, you could simply use require('path/to/file.json') to import the specified file as a JSON object/array. For example, to import src/assets/media.json (containing the array mentioned at the top), the syntax would be:

// e.g., in src/components/Foo.vue
const media = require('../assets/media.json')
console.log(media) // => [ "foo", "bar" ]

demo

techinplanet staff

techinplanet staff


Windows 10 Kaufen Windows 10 Pro Office 2019 Kaufen Office 365 Lizenz Windows 10 Home Lizenz Office 2019 Home Business Kaufen windows office 365 satın al follower kaufen instagram follower kaufen porno