首页 > 解决方案 > 将文件内容读入vue组件内的数组

问题描述

目录结构

在我的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入一个数组,然后用这些填充轮播src。我一直在尝试使用 Webpack 的require.context功能,但出现module not found错误。

我怎样才能得到这个工作?

标签: javascriptvue.jswebpackvuejs2

解决方案


您可能应该安装https://github.com/webpack-contrib/raw-loader#getting-started(用于 webpack 读取 txt 文件的加载器),在您的 vue.config.js 中配置它,您应该能够像导入这:从'raw-loader!./file.txt'导入txt;而是使用要求。


推荐阅读