In Vue, you can dynamically load a JavaScript file containing a JavaScript object during runtime

I'm in the process of developing a no-code application with Vue. I have come across an issue where I cannot add functions to a JSON file that I want to import at runtime. As a workaround, I decided to use a JavaScript or TypeScript file to store the JSON object like so:

export {
  "is": "button",
  "props": {
    "type": "button"
  },
  "events": {
    "click": () => {
      // do something
    }
  }
}

Currently, my aim is to trigger the import when Vue creates the component.

{
  created () {
    // code to import here
  }
}

I've experimented with two methods:

  1. Adding a script tag, but I need a way to store it first, like using window
  2. Using import, which only supports local files

As of now, I store these files on the backend and load them as needed on the frontend. Is there a more efficient solution available? Any help would be greatly appreciated. Thank you!

Answer №1

Perhaps you are looking to implement a deferred module loading approach, similar to using Webpack for code splitting. For more information, you can check out this resource:

I'm hesitant to fully endorse the method you're proposing, but if you do decide to proceed, your solution may involve:

  1. Sending an HTTP request to fetch the content of your file as plain text (not JSON). The file itself could be a .js file containing function definitions within an object literal ({ a: ..., b: ..., c: ... }).
  2. Upon receiving the text, evaluating it using eval(...the response) and storing it in a local variable for usage. Keep in mind that if the code relies on any dependencies, you will need to handle transferring those as well.

Admittedly, this process is quite complex and likely not very practical. Code splitting is usually beneficial for larger applications; for smaller ones, the overhead of additional requests might outweigh the benefits of splitting the initial bundle.

For a smoother experience, consider leveraging Vue's built-in dynamic import system instead of creating a custom solution. Ultimately, the best approach will depend on your specific goals in this particular scenario.

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

Web Browser Fails to Set Cookie during an Ajax Request

I am facing a perplexing issue. I have an AJAX call that triggers the processing of a login form and generates a cookie upon successful login. However, the web browser is failing to recognize the cookie. Upon troubleshooting, I have narrowed it down to so ...

What is the best way to execute a method in a component for each iteration in an *ngFor loop in Angular 2

Is there a way to call a method for each iteration of *ngFor and pass the iterated variable as a parameter? For example: <li *ngFor="let element of componentModel | keys">{{element.key}}--{{element.value}}</li> Then, in the component, I have ...

Displaying only one modal at a time with Bootstrap 3

The code snippet below is used to trigger my newsletter modal: $(window).load(function(){ if (sessionStorage.getItem("is_seen") === null) { setTimeout(function(){ $('#newsletter_modal').modal('show&ap ...

Adaptable material for collapsible panels

I'm facing a challenge with implementing an accordion menu. My goal is to have a 4 column layout that transforms into an accordion menu when the browser width is less than 600px. It almost works as intended, but there's a glitch. If you start at ...

Having trouble closing the phonegap application using the Back Button on an Android device

I've encountered an issue with my code for exiting the application. It works perfectly the first time, but if I navigate to other screens and then return to the screen where I want to close the app, it doesn't work. <script type="text/javascr ...

Transferring HTML content using jQuery AJAX and PHP

Can anyone help me with displaying the content of a division on one page to another? <div id="box-cont" class="box-content"> <?php echo $stat;// Includes multiple images and s ...

Images Are Failing to Load on the Webpage

I'm facing an issue with appending pictures of restaurants to dynamic div IDs. When I make the div ID static, the pictures show up fine from the server, but when I try to make it dynamic, the images don't get appended. Can someone please assist m ...

Unpacking data types from an array of classes in TypeScript: A step-by-step guide

I am working on a function that takes an array or rest of Typescript classes as input and resolves, returning their instances. However, I'm struggling to ensure correct typing for it. If I take one class as an example: class Base { isBase = true ...

Having trouble setting a JavaScript variable with a PHP session variable

In my PHP file, I have a session variable named $_SESSION['SESS_USER_TYPE'] set to a 2-character string. After the PHP script redirects to an HTML file, I need to retrieve this session variable in a JavaScript variable. This is how I am attempti ...

What is the reason for being unable to submit the value of an input that is disabled?

When I try to save the value of an input field that is disabled and has the required attribute, I receive an error message stating that "field_name is required". Why am I unable to insert a value when the input field is disabled? <input disabled type=&q ...

Ways to access an Environment variable within VueJs components

Seeking assistance from anyone. I'm trying to figure out how to access an environment variable that's stored in the .env file of a Laravel project from within a vuejs component. .env file SECREAT_KEY=<My secreat key here> I need to retr ...

Refresh your webpage automatically using Typescript and Angular

Currently facing an issue and seeking assistance. My query is regarding reloading a website after 5 minutes in a Typescript/Angular application. Can anyone help with this? ...

Exploring Node.js: Managing Memory Consumption for Efficiency

I'm currently setting up multiple Node applications on one server, and I'm particularly worried about memory usage. Is there a specific amount of physical memory needed for a basic Node.js express service to run? Also, is there a method to limit ...

Is there a way for me to manage the appearance of the printed document's layout?

I have successfully added 3 print buttons to my website, each one designed to print a specific portion (div) of the webpage. Here is the code snippet for this functionality: function printPage(id) { var html="<html>"; //html+="<link rel="st ...

Accessing references within composable functions

Presented below is the code for my Vue3 application: <template> {{ names_data }} </template> <script> import getData from "./composables/getData" export default { name: "App", setup() { var filenames = [&qu ...

Dealing with enum values in Jest tests when using Prisma can be tricky. The error message "Group[] not assignable to

Here is an example of my prisma postgresql schema: model User { id Int @id @default(autoincrement()) uuid String @db.Uuid createdat DateTime @default(now()) @db.Timestamp(6) updatedat DateTime @updatedAt first ...

The filter() function seems to be failing to produce any results even though the callbackFn is functioning properly

I've created a function to filter certain JSON elements in an array using Vue 3. Here is the data structure: [ { "UID_Person": "160a5b9e-c352-39e3-802b-9cfcc126da77", "FirstName": "Maxi", ...

Order of Execution for Nested Promises

Curious about nested promises, I came across this coding challenge in my tutorials. Can someone shed some light on the execution order of this code? new Promise((resolve) => { new Promise((res) => { console.log("c"); resolve(3); ...

Having trouble setting the selected option in Jquery by value?

I have exhausted all options found on the internet. What could I be overlooking? The desired option is not getting selected. Here is the troublesome section of code. I have also included some other attempts that I have commented out. If it helps, this li ...

Issue with integrating Google Spreadsheet as the data source for a Next.JS website: updates are not reflecting on the website pages

The website for this restaurant was created by me, using Google Spreadsheet to populate the menu pages. I chose this method for its simplicity and familiarity to the client. I'm utilizing the google-spreadsheet package to extract necessary informatio ...