Load the file's contents into an array within a Vue component

https://i.sstatic.net/gxcYi.png

My media.txt file contains the following URLs:

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

Incorporating a 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 am attempting to retrieve images from the media.txt file and display them in the carousel src. Despite using Webpack's require.context function, I am encountering a module not found error.

Any suggestions on how to resolve this issue?

Answer №1

If you're looking to bring in a string array (JSON) into a variable, make sure the string array is enclosed with square brackets like this:

[
  "example1",
  "example2"
]

Using

require.context(dirPath, useSubDirs, filenameRegex)
in this scenario is not the best choice, as it is used to import multiple files from a specific directory. For example, the code snippet below instructs Webpack to load files with extensions like *.png, *.jpg, and *.mp4 from a directory named ../static/media.txt (which might be a file instead).

require.context('../static/media.txt', false, /\.png$|\.jpg|\.mp4/) // AVOID USING THIS

Instead, you can simply rely on require('path/to/file.json') to bring in the specified file as a JSON object/array. For instance, to import src/assets/media.json (containing the array mentioned earlier), you can use the following syntax:

// For instance, in src/components/Foo.vue
const media = require('../assets/media.json')
console.log(media) // => [ "example1", "example2" ]

Check out this demo

Answer №2

If you want to read txt files in webpack, consider installing the raw-loader from https://github.com/webpack-contrib/raw-loader#getting-started. Once installed, configure it in your vue.config.js. After that, you can import txt files like this: import txt from 'raw-loader!./file.txt'; instead of using require.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Populate a bootstrap-select dropdown menu with an array of choices

After creating a table using datatables and adding an empty dropdown select on the footer with Bootstrap-select, here is the code snippet: <tfoot> <tr> <th><select class="selectpicker" multiple></select>< ...

The console in React displays values, but fails to render them on the DOM

I am attempting to dynamically load options for a select element based on another select's value. I pull the data from an array that will eventually contain more information. The issue I am facing is that even though I successfully filter the data, t ...

Exciting discovery within my coding for US Number formatting!

I am currently working on formatting 10 digits to resemble a US telephone number format, such as (###) ###-####. Although my code successfully achieves this goal, it also has an unexpected issue that I'm struggling to identify. Specifically, when ente ...

Eliminate redundant tags using jQuery

I have a code snippet that I need help with. I want to check for duplicates and if found, display an alert stating that it already exists so users can't insert the same word/tag again. Can someone please assist me? <div id="tags"> <span>a ...

Here's a way to programmatically append the same icon to multiple li elements generated using document.createElement:

I am new to creating a to-do app and need some guidance. When a user enters a task, I successfully create a list item for that task. However, I am unsure how to add a delete icon next to the newly created li element. Can someone please help me out? Below ...

"Utilizing multiple materials in a single obj file using the power of three.js

As I work with three.js to load an obj file featuring a ring adorned with pearls, I face a challenge. The obj file lacks an mtl file, a result of the exporting software - possibly Rhinoceros - not including it (as per the graphic designer's explanatio ...

Retrieve an array field across various documents and combine the elements to form a single object

Consider a scenario where there is a users collection. Each user document includes an array of posts called posts. The goal is to query this collection as follows: Retrieve 2 posts, starting at index Nstart and ending at index Nend, from each user in the ...

I am currently working on creating a drag select feature in React completely from scratch, but I'm facing some challenges with

Check out this code I created for drag selection: Here's the item generation code: const items = [ 1, 2, 3, ...94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, ].map((i) => ({ item: i, selected: i === 1 })); This is the actual code responsi ...

What is the best way to transfer data from MongoDB (utilizing the Mongous module) to a Node.js view (using the Jade templating

Hello everyone, I have a quick question regarding passing data from a model (database) into a view. I am using Express, Mongous (not Mongoose) to access MongoDB, and Jade for my views. Despite trying to use Mongoose, I have not been successful in achieving ...

Encountering special symbols in the ID of a form element triggers an error message in jQuery validator, stating 'Unrecognized expression'

One of the challenges I am facing is that I have a form with elements that have ids containing special symbols. For example: The id="$FormData[1]$PersonData[1]$PhysicalPerson[1]$PersonName[1]$Affix[@type='qualification' and @position='prefi ...

Update the database with the new values and display them in an HTML table

I am working with a table that looks like the one below: <script> $("#edit").hide(); // Initially hide the edit table $("#update").click(function() { $("#edit").toggle(); $("#shown").toggle(); ...

Update the function to be contained in a distinct JavaScript file - incorporating AJAX, HTML, and MySQL

Currently, I am working on a project and need to showcase a table from MySQL on an HTML page. The JavaScript function in my code is responsible for this task, but due to the Framework 7 requirement, I must separate the function into a different .js file ra ...

Bring life to the process of adding and removing DOM elements through animation

I am seeking to provide an engaging and interactive experience for my users while ensuring responsiveness. To achieve this goal, I have decided to learn more about web development by creating a card game. My current setup involves clickable elements that ...

Disable the time selection feature in the text input field

Despite seeing the same question asked before for this issue, I am looking for a solution that does not involve replacing the textbox with the same ID. When Timepicker is selected in the dropdown menu timepicker, it should activate in the textbox (which i ...

AngularJS is receiving an array of null inputs

I have a form where data from my DB is displayed through WebApi. One of the controls will contain an array of values. There is a scenario where the user can edit and save it using the PUT function. Controller : $scope.Put= function () { $scope.i ...

Efficiently sending data to Service Bus from an HTTP-triggered function

How can I link the output to service bus? I've configured an out binding in my Azure function: { "queueName": "testqueue", "connection": "MyServiceBusConnection", "name": "myQueueItem", "type": "serviceBus", "direction": "out" } I started ...

Enhance Your Form Validation with jQuery UI Dialog Plugin

Currently, I am utilizing the bassistance validation plugin for form validation. I have set up a pop-up modal dialog box to contain a form that requires validation, but for some reason, the form is not getting called. I have checked all my ID's and re ...

updating rows in a table

Currently, I have a grid array filled with default data retrieved from the database. This data is then displayed on the front end in a table/grid format allowing users to add and delete rows. When a row is added, I only want to insert an empty object. The ...

Click the "Add" button to dynamically generate textboxes and copy the contents from each

I am working on a project where I have an Add button and 6 columns. Clicking on the Add button generates rows dynamically, which can also be deleted. My challenge is to copy the content of one textbox into another in 2 of the columns. This copying function ...

Ways to determine the name of the calling function in an AJAX or XMLHttpRequest request?

I am currently exploring ways to programmatically identify the function name responsible for triggering an Ajax call in JavaScript or jQuery within an existing codebase. As I delve into instrumenting a large existing codebase, I am seeking to pinpoint the ...