How can I pass a variable name as an argument in Vue?

I am exploring ways to create a method that can efficiently load and assign JSON files to dynamic variables. Despite my efforts, varA and varB are not being populated as expected:

  data() {
    return {
      varA: Array,
      varB: Array
    }
  },

  mounted(){
    this.loadJSON("example.com/fileA.json", this.varA);
    this.loadJSON("example.com/fileB.json", this.varB);
  },

  methods: {
    loadJSON(uri, target) {
      fetch(uri)
        .then(res => res.json())
        .then((out) => {
          target = out;
        })
        .catch(err => {
          throw err;
        });
    },
  }

I have also experimented with defining varA and varB as computed properties, but encountered the same issue. Is there a way to achieve this without explicitly specifying variable names in loadJSON()?

Answer №1

If you're looking for an alternative, consider using Vue.set:

  mounted(){
    this.loadContent("dataA");
    this.loadContent("dataB");
  },

  methods: {
    loadContent(url, target) {
      const vm = this;
      fetch(url)
        .then(response => response.json())
        .then((data) => {
          Vue.set(vm, target, data);
        })
        .catch(error => {
          throw error;
        });
    },
  }

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

The Link tag in the Hero.jsx file of Next.js is malfunctioning and failing to redirect to the intended URL

Having a problem with the button in my Hero.jsx component, part of the Page.js implementation. The button uses a Link tag to redirect to the url.js page, but it's not working as expected and showing an Error 404 page instead. I'm new to Next.js s ...

What could be the reason that a basic click function fails to locate the selector?

I have created a quick JavaScript module that opens an image and fades out a container to reveal the image. The HTML markup for the image looks like this: <div style="margin-bottom:1px;" class="rsNavItem rsThumb front"> <di ...

AngularJS array value with HTML tags is not displaying properly upon invocation

In Angular, I have an array that has the following structure: $scope.posts = [ { "ID" : id(), "Title" : "A", "Company" : "Company A", "Location" : "San Francisco, CA", "Date" : "2016-06-20", "Description ...

Incorporating the unshift method in JavaScript: A Step-by-

I'm looking to create a new function with the following requirements: Function add(arr,...newVal){ } array = [1,2,3]; add(array,0) console.log(array); //I want this to output [0,1,2,3] I tried creating the function similar to push like this: ...

Is it possible to invoke a helper function by passing a string as its name in JavaScript?

I'm encountering a certain issue. Here is what I am attempting: Is it possible to accomplish this: var action = 'toUpperCase()'; 'abcd'.action; //output ===> ABCD The user can input either uppercase or lowercase function ...

having difficulty iterating through the data using map function

When attempting to use the map function in React Material UI to display an array of data in a select box, I encountered the error TypeError: Cannot read properties of undefined (reading 'map') while using the following code. Can anyone help me id ...

Tips for targeting the Next button press event and setting focus in an Ionic-vue application

Struggling to shift focus from one input to another on Android/iOS keyboard using the next button? The setFocus method lacks examples, making it difficult to implement. Has anyone successfully achieved this before and can provide an example? Here's ...

At that specific moment, a plugin is active to monitor the execution of JavaScript functions

Similar to how Fiddler allows you to monitor the communication between client and server, I am looking for a tool that can analyze all network traffic generated by client-side JavaScript on a webpage. Warm regards, bd ...

Using jQuery.ajax and not retrieved using a GET request

I'm attempting to extract the value (adults) from a select option field using a GET request with AJAX. I am able to extract the value from the URL by displaying an alert with the URL in the jQuery function. However, I am unable to retrieve the value w ...

The search functionality in react-native-google-places-autocomplete seems to be experiencing issues as it is not displaying

I am currently working on a React Native component that incorporates a Google search feature for locations. To achieve this, I have utilized the Google Places API in hopes of enabling autocomplete functionality when users begin typing a city or address. I ...

Tips for customizing Material-UI Switch button appearance

Is there a way to remove the box-shadow on the thumb of the Switch button when it's disabled? I've tried various methods like adding the box-shadow in the switchBase and removing it from the thumb, but it affects the parent element as well. Anoth ...

When I click the login button, a .ttf file is being downloaded to my computer

I have encountered an issue with my web application where custom font files in .ttf, .eot, and .otf formats are being downloaded to users' local machines when they try to log in as newly registered users. Despite attempting various solutions, I have b ...

Whenever I try to run npm start, my webpack is not able to locate my index.html page

Recently delving into the world of node.js and its packages, I initiated by executing npm init to lay out the package.json structure shown below: { "name": "test", "version": "1.0.0", "description": & ...

Encountered SyntaxError: An unexpected token has been found while integrating leaflet with flask

Despite adding all necessary scripts and configuring my API_KEY in config.js, I keep getting an error message saying "Uncaught SyntaxError: Unexpected token." I have double-checked my API key multiple times, and it seems to be correct. Here is a snippet f ...

Obtain information about a div element while scrolling

Looking to enhance my social feed page by adding a view count feature for each post. The challenge is figuring out how to keep track of views as the user scrolls down the page. Any suggestions? ...

Express JS backend causing CSS file to fail to load in React project

After doing some research on Stack Overflow, I came across a few solutions but none of them seemed to work for my specific situation. I am currently attempting to serve my React website from an Express backend server. Here is the layout of my folders: cli ...

Transferring data in PDF format through email with the help of PHPMailer and html2pdf

Having trouble sending PDF or PNG files over email despite multiple attempts. Despite reading countless articles on the topic, nothing seems to be working as suggested. Can anyone provide assistance? I am using PHPMailer along with html2pdf and html2canva ...

Focusing on the final (but not ultimate) elements within a specified tag

I am facing a challenge with an HTML structure containing multiple instances of a certain element along with two p elements beneath each: <some_tag></some_tag> <p></p> <p></p> <some_tag></some_tag> <p> ...

What could be causing the target to malfunction in this situation?

Initially, I create an index page with frames named after popular websites such as NASA, Google, YouTube, etc. Then, on the search page, <input id="main_category_lan1" value="test" /> <a href="javascript:void(0)" onmouseover=" window.open ...

Avoiding the utilization of HTML forms

Is it acceptable to send form information using jQuery instead of creating an HTML form? By skipping the traditional HTML form and using $.ajax in jQuery, are there any security, performance, or semantic issues to be concerned about? Does this approach a ...