javascript - 将文件内容读入Vue组件中的数组-LMLPHP
在我的media.txt文件中,我有:

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

我有以下Vue旋转木马组件:
<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>

我想将media.txt文件中的图像读取到一个数组中,然后用它们填充carouselsrc。我一直在尝试webpack的require.context功能,但我得到一个module not found错误。
我怎样才能让这工作?

最佳答案

看起来您正试图将字符串数组(json)导入到变量中。字符串数组应该用方括号分隔,如下所示:

[
  "foo",
  "bar"
]

require.context(dirPath, useSubDirs, filenameRegex)不是此处使用的适当api,因为该方法从指定目录导入多个文件。例如,下面的代码告诉webpack从名为*.png的目录加载*.jpg*.mp4../static/media.txt文件(可能实际上是一个文件)。
require.context('../static/media.txt', false, /\.png$|\.jpg|\.mp4/) // DON'T DO THIS

相反,您可以简单地使用require('path/to/file.json')将指定的文件导入为json对象/数组。例如,要导入src/assets/media.json(包含顶部提到的数组),语法如下:
// e.g., in src/components/Foo.vue
const media = require('../assets/media.json')
console.log(media) // => [ "foo", "bar" ]

demo

关于javascript - 将文件内容读入Vue组件中的数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56012736/

10-08 22:32
查看更多