Tips on storing information within a Vue instance

Seeking a simple solution, all I need is to save data retrieved after an AJAX post in the Vue instance's data. See below for my code:

const VMList  = new Vue({
  el: '#MODAL_USER_DATA',
  data: {
    user: []//,
    //userAcc: []
  },
  methods: {
    getUserAcc: function ( userID ) {

      this.user = { _id : userID };

      var self = this
      $.ajax({
        url: "/listuser",
        type: "POST",
        data: this.user,
        success: function(data) {
          this.user = data ;
          //this.userAcc = Object.assign({}, this.userAcc, data );
          alert(JSON.stringify(this.user));//display correct user data
          $('#popupDeleteModal').modal('show');
          alert(JSON.stringify(data));//display entire json object with good content
        },
        error: function(err) {
          console.log('error: ',err);
        },
      });

    }
  }
});

After triggering the getUserAcc(id) method and checking the VMList.user value in the browser console, I noticed that only the id is displayed. It seems like the data is getting reset after the function ends. How can I ensure that the data from the AJAX post request is stored in the user object within the data:{...} section?

Thanks for your assistance!

Answer №1

The issue arises when the reference of this inside your ajax return function no longer points to the vue instance.

A workaround is to store the reference of the this keyword in a variable within the function like so:

getUserAcc: function ( userID ) {
  var that = this;
  this.user = { _id : userID };
  $.ajax({
    url: "/listuser",
    type: "POST",
    data: this.user,
    success: function(data) {
      that.user = data;
      //Continue with your code
    },
    error: function(err) {
      console.log('error: ',err);
    },
  });
}

For more insights on how the keyword this works, check out this link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

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

Enrollment of Vue components

After importing the component into the JavaScript file, I added it to the index.vue file as follows: import fmsSubUnitDetails from '../subunitDetails'; export default{ components: { fmsSubUnitDetails }, } Despite this, I am still encount ...

Leveraging split and map functions within JSX code

const array = ['name', 'contact number'] const Application = () => ( <div style={styles}> Unable to display Add name & contact, encountering issues with splitting the array). </div> ); I'm facing difficul ...

What is causing my array of objects to constantly accumulate undefined elements?

My quick sort function implementation for the object users_total_likes is behaving unexpectedly. When compiled and run in the terminal or browser, it adds undefined values causing a TypeError: if(users[i][key] >= users[hi][key] && users[j][key] ...

Create a project using Next.js and integrate it with the tailwindcss framework

My application utilizes TailwindCSS and NextJs. I am facing an issue where certain classes are not working after running npm run start, following a successful run of npm run dev. For example, the classes h-20 / text-white are not functioning as expected, w ...

Browser Compatibility with AngularJS

Encountering an issue with AngularJS compatibility - are there any features not supported by Google Chrome? We have developed the AngularUI Calendar and utilized the JSFiddle link below: http://jsfiddle.net/joshkurz/xqjtw/52/ The UI calendar works on Fi ...

`How can I effectively integrate react-i18next with the Semantic UI label element?`

Currently, I am working with Semantic UI along with the integration of [react-i18next][2]. My goal is to enable translation for label strings, but these labels include HTML tags, such as span. Unfortunately, the system only allows hardcoded or variable s ...

npm not working to install packages from the package.json file in the project

When using my macbook air, I encounter an issue where I can only install npm packages globally with sudo. If I try to install a local package without the -g flag in a specific directory, it results in errors. npm ERR! Error: EACCES, open '/Users/mma ...

Leveraging PapaParse for CSV file parsing in a React application with JavaScript

I am encountering an issue with reading a CSV file in the same directory as my React app using Javascript and Papaparse for parsing. Below is the code snippet: Papa.parse("./headlines.csv", { download: true, complete: function(results, f ...

What is the best approach to determine the numerical equivalents of options in a dropdown menu using PHP and JS

Hey guys, I'm really stuck on this problem and I can't seem to find a helpful tutorial anywhere. I've got a form with two drop-down menus, each with a "value" attribute. What I want is for users to be able to select an item from both drop-do ...

An issue is preventing the Angular 2+ http service from making the requested call to the server

I am looking to create a model class that can access services in Angular. Let's say I have the following endpoints: /book/:id /book/:id/author I want to use a service called BooksService to retrieve a list of Book instances. These instances should ...

Wait for the canvas to fully load before locating the base64 data in HTML5

Wait until the full canvas is loaded before finding the base64 of that canvas, rather than relying on a fixed time interval. function make_base(bg_img, width, height) { return new Promise(function(resolve, reject) { base_image = new Image(); base_imag ...

Finding the correct column in a drop-down menu based on a table array using AngularJS

In my controller, I have data like this: $scope.operationData = [ { "label" : "Inventory", "labelType" : "Master Tables", "type" : "PROCESSOR", "outputStreams" : 1, "elementType" : "TABLE", "name" : ...

Unable to refresh JSON data in Datatables

Ensuring this operation is simple, I am following the documentation. An ajax call returns a dataset in JSON format. The table is cleared successfully, but even though data is returned according to the console statement, the table remains empty after the su ...

Mac users may experience lag when using Javascript parallax effects

I created a parallax page where the background image changes using JavaScript translateY(- ... px)' similar to what you see on the firewatch website. On Windows, the parallax effect works smoothly. However, on macOS it is smooth only in Safari. All ...

Move the items downwards to occupy any empty space vertically

Just a quick overview of the code I'm working with (I am using Material UI in React). This container is meant to hold chat messages exclusively. const ChatContainer = ({ chatMessages }) => { const classes = useStyles(); return ( <Paper ...

Logging in with oidc-client and IdentityServer4 on separate domains

I am currently working on a VueJs application hosted on localhost which utilizes the oidc-client.js library for logging in to an IdentityServer4 server located in a production environment on another domain. Upon successful login, I am redirected back to t ...

Exploring the functionality of ngTemplateOutlet, the implementation of @ContentChild, and the benefits of using ng

Lately, I've been dedicating more time to grasp the concepts presented in the blog post titled Creating Reusable Components with NgTemplateOutlet in Angular If you want to see the code in action, it's available on stackblitz. Within the UsageEx ...

Bundling sub-components using Rollup for NodeJS application packaging

My ES6 library consists of several sub-modules arranged like this: - package.json - lib - my_package - file1.js - file2.js - sub_module1 - file3.js - file4.js Currently, I import modules within my package using file resolution r ...

How to correctly serialize nested maps in JQuery ajax data for sending?

var locationData = { "location" : { "name" : $("#user_loc_name").val(), "street_address" : $("#user_loc_street_address").val(), "city" : $("#user_loc_city").val(), "province" : ...

Warning: Unhandled promise rejection occurred while running the test

Currently delving into the world of selenium with a focus on testing the registration page. I've crafted a registration page class equipped with methods for monitoring registrations. However, upon attempting to execute a test within the application cl ...